使用pdf.js将PDF嵌入到网页中

时间:2013-11-02 01:13:26

标签: javascript pdf pdf.js pdf-conversion

pdf.js对于像我这样的新手来说有点大项目。正如大多数帖子所说,这个项目是将PDF文件嵌入网络的绝佳工具。但是我很难弄清楚如何使用它。

我想知道的是如何使用 pdf.js嵌入本地PDF文件?

1 个答案:

答案 0 :(得分:1)

您可以提供相对网址,例如pdfPath="pdf/TestDocument.pdf"

以下是使用Github上提供的示例创建的示例代码:

PDFJS.workerSrc ='PATH_TO_WORKER_LOADER/worker_loader.js';
pdfDoc = PDFJS.getDocument(pdfPath);
pdfDoc.then(renderPdf);

function renderPdf(pdfDoc) {

      pdfNumPages = pdfDoc.numPages;

    pdfDoc.getPage(1).then(renderPage);
}

function renderPage(page) {

    var viewport = page.getViewport(scale);
    var $canvas = jQuery("<canvas></canvas>");
    //Set the canvas height and width to the height and width of the viewport
    var canvas = $canvas.get(0);
    var context = canvas.getContext("2d");
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    //Append the canvas to the pdf container div (refer a div in your HTML file)
    var $editorTextArea = jQuery("#editorTextArea");
    $editorTextArea.css("height", canvas.height + "px").css("width", canvas.width + "px");
    $editorTextArea.append($canvas);

    var canvasOffset = $canvas.offset();
    var $textLayerDiv = jQuery("<div />")
        .addClass("textLayer")
        .css("height", viewport.height + "px")
        .css("width", viewport.width + "px")
        .offset({
            top: canvasOffset.top,
            left: canvasOffset.left
        });

    //The following few lines of code set up scaling on the context if we are on a HiDPI display
    var outputScale = getOutputScale(context);
    if (outputScale.scaled) {
        var cssScale = 'scale(' + (1 / outputScale.sx) + ', ' +
            (1 / outputScale.sy) + ')';
        CustomStyle.setProp('transform', canvas, cssScale);
        CustomStyle.setProp('transformOrigin', canvas, '0% 0%');
    }

    context._scaleX = outputScale.sx;
    context._scaleY = outputScale.sy;
    if (outputScale.scaled) {
        context.scale(outputScale.sx, outputScale.sy);
    }
        var renderContext = {
            canvasContext: context,
            viewport: viewport,
            textLayer: textLayer
        };
        page.render(renderContext);
    });
}