Search code examples
node.jssvgpdfmakenode-pdfkit

Node.js: Adding SVG to a specific page of PDF by pdfmake


I am trying to create PDF content by pdfmake. However, pdfmake do not support adding SVG at v0.1.38. So I use SVG-to-PDFKit to achieve that. Here is my code:

var printer = new pdfMakePrinter(fontDescriptors);

var doc = printer.createPdfKitDocument(pdfDoc);

SVGtoPDF(doc, s.data, s.x, s.y, s.options); // add this line for SVG-to-PDFKit to insert SVG while s contain SVG data

var chunks = [];
var result;

doc.on('data', function(chunk) {
    chunks.push(chunk);
});
doc.on('end', function() {
    result = Buffer.concat(chunks);
    resolve(result);
});
doc.end();

SVG is successfully added to the last page. How to add the SVG to a specific page?


Solution

  • After reading the source code and document, adding { bufferPages: true } fix your need perfectly.

    var printer = new pdfMakePrinter(fontDescriptors);
    
    var doc = printer.createPdfKitDocument(pdfDoc, { bufferPages: true }); // magic here!
    doc.switchToPage(x); // to page x, where x start from 0
    
    SVGtoPDF(doc, s.data, s.x, s.y, s.options); // add this line for SVG-to-PDFKit to insert SVG while s contain SVG data
    
    var chunks = [];
    var result;
    
    doc.on('data', function(chunk) {
        chunks.push(chunk);
    });
    doc.on('end', function() {
        result = Buffer.concat(chunks);
        resolve(result);
    });
    doc.end();