SVG-to-PDFKit
SVG-to-PDFKit copied to clipboard
Browser freezes while converting a very large svg
Hi, currently when I try to make PDF from a very large SVG, it stops the browser for a while. I want to show the loading gif to make users wait. However, the gif freezes as well. It plays again when the PDF has been done. Can you please suggest me a way to resolve this problem?
-
Using a Worker can be a solution, it will remain very slow (about 40 seconds for the #20 svg file) but the browser doesn't freeze, so the gif will play normally. If you need to do other tasks with the PDFDocument it will be more difficult to use Workers
-
It is certainly possible to improve the performance of SVG-to-PDFKit but I'm not a javascript expert nor a performance-improving expert...
// file 'worker.js':
importScripts('pdfkit.js', 'blobstream.js', 'svgtopdfkit.js');
this.onmessage = function(msg) { // receive the svg code from the main thread
let doc = new PDFDocument();
SVGtoPDF(doc, msg.data, 0, 0);
let stream = doc.pipe(blobStream());
stream.on('finish', function() {
postMessage(stream.toBlob('application/pdf')); // send the pdf blob to the main thread
});
doc.end();
}
// main file:
let worker = new Worker('worker.js');
worker.onmessage = function(msg) { // receive the pdf blob from the worker
let pdfUrl = URL.createObjectURL(msg.data);
};
worker.postMessage(svgCode); // send the svg code to the worker