Skip to content

Instantly share code, notes, and snippets.

@w33ble
Last active June 8, 2023 12:16
Show Gist options
  • Select an option

  • Save w33ble/38c5e0220d491148de1c to your computer and use it in GitHub Desktop.

Select an option

Save w33ble/38c5e0220d491148de1c to your computer and use it in GitHub Desktop.

pdfmake

Use in node.js

The module on npm exposes the pdfmake Printer, which the docs themselves do not cover. Using it is pretty simple though.

var fontDescriptors = {}; // required font setup, see ...
var docDefinition = {}; // this is what you see in all the docs
var Printer = require('pdfmake');
var printer = new Printer(fontDescriptors);

// get a reference to the PdfKit instance, which is a streaming interface
var pdfDoc = printer.createPdfKitDocument(docDefinition);

// pipe to a file or response object
function streamTo(pdfDoc) {
  // writeStream can be an fs object, response object, etc
  var writeStream = fs.createWriteStream('pdfs/output.pdf');
  var pdfDoc = printer.createPdfKitDocument(docDefinition);
  pdfDoc.pipe(writeStream); // streaming interface
}

// turn the stream into a Buffer
// Usage: getDoc(pdfDoc, function (err, buffer, pages) { var base64 = buffer.toString('base64'); /* app logic */ });
function getDoc(pdfDoc, cb) {
  // buffer the output
  var chunks = [];
  
  pdfDoc.on('data', function(chunk) {
  	chunks.push(chunk);
  });
  pdfDoc.on('end', function() {
  	var result = Buffer.concat(chunks);
  	cb(null, result, pdfDoc._pdfMakePages);
  });
  pdfDoc.on('error', cb);
  
  // close the stream
  pdfDoc.end();
}

docDefinition

properties description default
header
footer
content
defaultStyle { fontSize: 12, font: 'Roboto' }
pageBreakBefore
styles
background
images
watermark

options

tableLayouts - ??? autoPrint - ???

@ThibaultJanBeyer
Copy link

Nice, thanks! This helped me a lot

@alphanumeric0101
Copy link

jee whiz, this was clutch thank you! can't believe this isn't mentioned in the documentation. if you want to simply print to fs then the examples folder is ok but if you want dataURI or Base64 it's like what the heck do I do as the getBase64() method doesn't exist.

@mostlyharmless2024
Copy link

epic resource, thanks a ton!

FYI - "retrun" on line 13 of the first code example

@szz-dvl
Copy link

szz-dvl commented Jan 19, 2019

Hi; I'm trying to use this to pipe the document through an express response object, however if I don't write the document first (using the deprecated function pdfDoc.write) the document is not properly generated. If anyone have an idea it will be welcome.

Thanks in advance.

Szz.

@szz-dvl
Copy link

szz-dvl commented Jan 19, 2019

Hey it is solved now, forgot to call doc.end() sorry for the inconvenience!

Thanks again.

Szz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment