用于pdf.js的Javascript Pdf导航

时间:2014-10-13 14:45:30

标签: javascript html navigation pdf.js

是否有可能使用pdf.js在html页面中呈现PDF并管理其导航? 对于导航我的意思是缩放和平移。我的目标是添加一些带有平移(上,下,左,右)的按钮进行缩放(放大,缩小,默认缩放),如果可能的话,自动平移文档,使其在点击中居中位置。

1 个答案:

答案 0 :(得分:2)

pdf.js的重点是在HTML5中呈现.pdf个文档。所以你所说的应该是可以实现的。该项目在Github上是quite well documented,应该是一个很好的起点。就用于缩放和调整的导航和其他切换按钮而言,它们已经明确实施herehere

因此,您可以先查看这些演示的来源,然后查看文档以满足您的需求。希望这能让你开始朝着正确的方向前进。我正在从其中一个演示中发布一些相关的代码片段:

  var pdfDoc = null,
  pageNum = 1,
  pageRendering = false,
  pageNumPending = null,
  scale = 0.8,
  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
 * finised. 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);

...

/**
 * Asynchronously downloads PDF.
 */
PDFJS.getDocument(url).then(function (pdfDoc_) {
    pdfDoc = pdfDoc_;
    document.getElementById('page_count').textContent = pdfDoc.numPages;

    // Initial/first page rendering
    renderPage(pageNum);
}