Click here to Skip to main content
14,667,169 members
Rate this:
Please Sign up or sign in to vote.
See more:
how to merge 2 pdf files into single pdf using client side technologies.

What I have tried:

var urls = [
    //'C:\Users\Khagesh\Desktop\PaySlip_Itentso\Payslip_Dec',
    //'C:\Users\Khagesh\Desktop\PaySlip_Itentso\Payslip_Nov'
       '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).
//
// PDFJS.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.
//
// PDFJS.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
 * 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);

/**
 * 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
    PDFJS.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);
    });
}


HTML:

<pre><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MergePDF.aspx.cs" Inherits="MergePDFUsingJS.MergePDF" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <base href="https://mozilla.github.io/pdf.js/" />
    <title></title>
    <script type="text/javascript" src="build/PDF1.js"> </script>
    <script type="text/javascript" src="build/pdf.js"></script>
<%--    /* <script src="web/compatibility.js"></script>*/--%>

   
</head>
<body onload="load()">
    <form id="form1" runat="server">
    <div>
            <button id="prev">Previous</button>
            <button id="next">Next</button>
               
            <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>

    </form>
</body>
</html>
Posted

Rate this:
Please Sign up or sign in to vote.

Solution 1

I believe that software is read-only; you would need software that can both read existings PDFs and write a new one (aka merged)
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

try to use bytesout like this :

var https = require("https");
var path = require("path");
var fs = require("fs");


// The authentication key (API Key).
// Get your own by registering at https://secure.bytescout.com/users/sign_up
const API_KEY = "***********************************";


// Direct URLs of PDF files to merge
const SourceFiles = [
    "https://s3-us-west-2.amazonaws.com/bytescout-com/files/demo-files/cloud-api/pdf-merge/sample1.pdf",
    "https://s3-us-west-2.amazonaws.com/bytescout-com/files/demo-files/cloud-api/pdf-merge/sample2.pdf"
];
// Destination PDF file name
const DestinationFile = "./result.pdf";


// Prepare request to `Merge PDF` API endpoint
var queryPath = `/v1/pdf/merge?name=${path.basename(DestinationFile)}&url=${SourceFiles.join(",")}`;
var reqOptions = {
    host: "bytescout.io",
    path: encodeURI(queryPath),
    headers: {
        "x-api-key": API_KEY
    }
};
// Send request
https.get(reqOptions, (response) => {
    response.on("data", (d) => {
        // Parse JSON response
        var data = JSON.parse(d)

        if (data.error == false) {
            // Download PDF file
            var file = fs.createWriteStream(DestinationFile);
            https.get(data.url, (response2) => {
                response2.pipe(file)
                .on("close", () => {
                    console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
                });
            });
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });
}).on("error", (e) => {
    // Request error
    console.log(e);
});
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100