Feature request: Browser support
Closed this issue · 4 comments
Hi. First off, thanks for this project. It's amazing.
It would be nice to make this library browser compatible (instead of relying on fs) so that for small PDFs a server solution isn't needed.
I've managed to make (a subset) of your code, browser compatible.
So instead of reading from file I used fetch() API:
const doc = new pdf.Document();
const inputFileBuffer = await (await fetch(url).arrayBuffer();
const ext = new pdf.ExternalDocument(inputFileBuffer);
doc.setTemplate(ext);
doc.addPagesOf(ext);
And instead of writing to file one can force browser download:
doc.end();
const buffer = await readableToBuffer(doc);
downloadBuffer({
buffer,
fileName: 'merged.pdf',
});
readableToBuffer & downloadBuffer implementations:
async function readableToBuffer(readable) { const chunks = []; for await (const chunk of readable) { chunks.push(chunk); } return Buffer.concat(chunks); }
function downloadBuffer({ buffer, fileName }) { // Create an invisible A element const a = document.createElement('a'); a.style.display = 'none'; document.body.appendChild(a);
// Set the HREF to a Blob representation of the buffer to be downloaded a.href = window.URL.createObjectURL( new Blob([buffer]), ); // Use download attribute to set set desired file name a.setAttribute('download', fileName);
// Trigger the download by simulating click a.click();
// Cleanup window.URL.revokeObjectURL(a.href); document.body.removeChild(a); }
The result: Merging small PDFs is amazingly fast. Faster than "pdf to canvas to jpeg/png" based solutions proposed out there in the web.
Do you have the complete code to share?
@ZaunSupremoXV I have full code at https://github.com/Munawwar/merge-pdfs-on-browser/blob/master/public/pdfjs-approach/pdf-merger-js-adapted.js
But I later didn't go with this approach, as some specific PDFs crashed while merging (which I think I reported to pdfjs and is now fixed). So I went with server-side solution with PDFtk. However someone here can pursue taking that code and merging it into this repo.
Thanks @Munawwar
Implemented in #51 by @DanMHammer
released in pdf-merger-js@3.2.0 🎉