有没有办法在pdf.js中组合PDF? [英] Is there a way to combine PDFs in pdf.js?

查看:678
本文介绍了有没有办法在pdf.js中组合PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用pdf.js将现有的pdf文件合并到html5中并从中生成一个pdf

Well I want to combine existing pdf files in html5 using pdf.js and generate a single pdf out of them

这是可能的,我该怎么做?

Is this possible and how can I do this?

推荐答案

组合多个文档并只用pdf.js显示它们很容易 - 我只是基于以下示例攻击了以下示例简单的上一页/下一页查看器示例mozilla在他们的存储库中提供。

Combining multiple documents and merely displaying them as one with pdf.js is easily possible - i just hacked the following example based on the simple prev/next viewer example that mozilla provides in their repository.

    // If absolute URL from the remote server is provided, configure the CORS
    // header on that server.
    //
    var urls = [
        'http://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf',
        'http://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf'
    ];

    // Disable workers to avoid yet another cross-origin issue (workers need
    // the URL of the script to be loaded, and dynamically loading a cross-origin
    // script does not work).
    //
    // pdfjsLib.disableWorker = true;

    // In cases when the pdf.worker.js is located at the different folder than the
    // pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
    // shall be specified.
    //
    // pdfjsLib.workerSrc = 'pdf.worker.js';

    /**
     * @typedef {Object} PageInfo
     * @property {number} documentIndex 
     * @property {number} pageNumber
     */

var pdfDocs = [],
    /**
     * @property {PageInfo}
     */
    current = {},
    totalPageCount = 0,
    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;
    current = getPageInfo(num);
    // Using promise to fetch the page
    pdfDocs[current.documentIndex]
    .getPage(current.pageNumber).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 >= totalPageCount && current.documentIndex + 1 === pdfDocs.length) {
        return;
    }
    
    pageNum++;
    queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);

/**
 * @returns PageNumber
 */
function getPageInfo (num) {
    var totalPageCount = 0;
    for (var docIdx = 0; docIdx < pdfDocs.length; docIdx++) {
        
        totalPageCount += pdfDocs[docIdx].numPages;
        if (num <= totalPageCount) {
            return {documentIndex: docIdx, pageNumber: num};
        }
        num -= pdfDocs[docIdx].numPages;
    }
    
    return false;
};

function getTotalPageCount() {
    var totalPageCount = 0;
    for (var docIdx = 0; docIdx < pdfDocs.length; docIdx++) {
        totalPageCount += pdfDocs[docIdx].numPages;
    }
    return totalPageCount;
}

var loadedCount = 0;
function load() {
    // Load PDFs one after another
    pdfjsLib.getDocument(urls[loadedCount]).then(function (pdfDoc_) {
        console.log('loaded PDF ' + loadedCount);
        pdfDocs.push(pdfDoc_);
        loadedCount++;
        if (loadedCount !== urls.length) {
            return load();
        } 
        
        console.log('Finished loading');
        totalPageCount = getTotalPageCount();
        document.getElementById('page_count').textContent = totalPageCount;

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

<!DOCTYPE html>
<html>
    <head>
        <base href="https://mozilla.github.io/pdf.js/" />
        <meta charset="UTF-8">
        <title>Previous/Next example</title>
    </head>
    <body onload="load()">

        <div>
            <button id="prev">Previous</button>
            <button id="next">Next</button>
            &nbsp; &nbsp;
            <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
        </div>

        <div>
            <canvas id="the-canvas" style="border:1px solid black"></canvas>
        </div>

        <script src="build/pdf.js"></script>

    </body>
</html>

为了这个缘故在发送适当的CORS-Header的服务器上没有可靠的测试文档,这个例子只是合并默认文档的两个副本。如果您在自己的服务器上执行此操作,您当然可以添加在同一域下托管的任何文档,方法是将它们添加到 urls 数组中。

For the sake of not having reliable test documents out there on servers sending a proper CORS-Header, this example simply merges two copies of the default document. If you execute this on your own server, you can of course add any document hosted under the same domain by adding them to the urls array.

这篇关于有没有办法在pdf.js中组合PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆