1
我有一個函數,當單擊一個按鈕時調用並從servlet中加載一個文檔。然而,這應該是工作的方式是它加載一個多頁文檔,我有一個下一個/上一個按鈕,我發現了pdf.js網站。pdf.js查看器不正確地存儲圖像數據
發生了什麼事情是,當我加載文檔並查看文檔時,然後單擊以打開另一個文檔,當我點擊下一個/上一個時,它仍然在瀏覽較早的文檔。
例如,我最初將2頁文檔加載到查看器中。我可以點擊next/previous,像往常一樣瀏覽這個文檔的頁面。然後,我點擊一個按鈕來查看下一個文檔,這是一個3頁的文檔。我可以點擊下一頁查看3頁,但是當我點擊上一頁時,它會回到之前我最初加載的文檔。
下面是代碼:
function getDocument(){
var request = $.ajax({
url: "IndexServlet",
type: "POST",
data: {
token: "go",
fileName: $("#fileName").val(),
batchName: $("#folderName").val()
}
});
request.done(function(data) {
var pdfAsArray = convertDataURIToBinary(data);
function convertDataURIToBinary(dataURI) {
var base64 = dataURI;
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
PDFJS.disableWorker = true;
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = pageNum;
}
/**
* If another page rendering in progress, waits until the rendering is
* finished. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(pdfAsArray).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
});
}
難道您取消綁定document.getElementById('next')。addEventListener('click',onNextPage);聽衆? – async5
這似乎是這裏發生的事情,它幾乎就像前面的按鈕「功能」只適用於獲取文檔的第一次迭代 –