Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/bpampuch/pdfmake/llms.txt

Use this file to discover all available pages before exploring further.

When you call pdfmake.createPdf(docDefinition), pdfmake returns an OutputDocument object that wraps a lazy PDF generation pipeline. The actual rendering work begins the first time you call an output method. All output methods return a Promise. The internal buffer is computed once and cached — subsequent calls to getBuffer(), getBase64(), or getDataUrl() on the same instance reuse the cached result without re-rendering.

Getting an OutputDocument

// Node.js
const pdfmake = require('pdfmake/js/index');

// Browser
import pdfmake from 'pdfmake/build/pdfmake';

const docDefinition = {
  content: [
    { text: 'Sales Report — Q3', style: 'title' },
    { text: 'Generated on ' + new Date().toDateString() }
  ],
  styles: {
    title: { fontSize: 24, bold: true, margin: [0, 0, 0, 12] }
  }
};

const doc = pdfmake.createPdf(docDefinition);
// doc is an OutputDocument (browser) or OutputDocumentServer (Node.js)
The buffer cache applies to getBuffer(), getBase64(), and getDataUrl() — these all share a single internally computed bufferPromise. getStream() and write() operate on the raw PDFKit stream and are not cached. Do not call both getBuffer() and write() on the same OutputDocument instance; getBuffer() internally calls stream.end(), which will interfere with write().

Shared Methods

These methods are available in both the Node.js and browser builds. They inherit from the OutputDocument base class.

getStream()

Returns the Promise that resolves to the underlying PDFKit document stream. This is the lowest-level escape hatch; prefer getBuffer() unless you need to pipe the stream directly.
doc.getStream()
// Returns: Promise<object>  (PDFKit document stream)
getStream() exposes the raw PDFKit document object. Manually calling .end() or consuming the stream (e.g. piping it) will prevent getBuffer(), getBase64(), getDataUrl(), and write() from working correctly on the same instance, because those methods also consume the same underlying stream.
// Node.js — pipe to an HTTP response without buffering the entire PDF in memory
const pdfmake = require('pdfmake/js/index');
const http = require('http');

http.createServer(async (req, res) => {
  const doc = pdfmake.createPdf({ content: 'Streamed response' });
  const stream = await doc.getStream();

  res.setHeader('Content-Type', 'application/pdf');
  stream.pipe(res);
  stream.end();
}).listen(3000);

getBuffer()

Collects all PDF stream chunks and resolves with a single concatenated Buffer containing the complete PDF binary. The result is cached internally — subsequent calls on the same instance return the same promise without re-rendering.
doc.getBuffer()
// Returns: Promise<Buffer>
const pdfmake = require('pdfmake/js/index');

const doc = pdfmake.createPdf({ content: 'Hello, Node.js!' });

const buffer = await doc.getBuffer();
console.log(`PDF size: ${buffer.length} bytes`);

// Pass to an HTTP response
res.set('Content-Type', 'application/pdf');
res.send(buffer);

getBase64()

Resolves with the complete PDF encoded as a base64 string. Internally calls getBuffer() and then runs .toString('base64') on the result.
doc.getBase64()
// Returns: Promise<string>
const pdfmake = require('pdfmake/js/index');

const doc = pdfmake.createPdf({ content: 'Base64 example' });

const base64 = await doc.getBase64();

// Embed in a JSON API response
res.json({ pdf: base64 });

getDataUrl()

Resolves with a complete data: URL string in the form data:application/pdf;base64,<encoded-pdf>. Internally calls getBase64() and prepends the MIME prefix.
doc.getDataUrl()
// Returns: Promise<string>
const pdfmake = require('pdfmake/js/index');

const doc = pdfmake.createPdf({ content: 'Data URL example' });

const dataUrl = await doc.getDataUrl();
// dataUrl === 'data:application/pdf;base64,JVBERi0...'

Node.js Methods

The following method is available only in the Node.js build (OutputDocumentServer). It is not present in the browser bundle.

write()

Writes the PDF to the local file system at the given path. Internally pipes the PDFKit stream into a fs.WriteStream and waits for both the source stream and the write stream to close cleanly.
doc.write(filename)
// Returns: Promise<void>
filename
string
required
The destination file path. Relative paths are resolved from the current working directory of the Node.js process. The directory must already exist; write() does not create intermediate directories.
write() consumes the raw PDFKit stream directly. Do not call getBuffer(), getBase64(), or getDataUrl() on the same OutputDocument instance after calling write(), as the stream will already be consumed.
const pdfmake = require('pdfmake/js/index');
const path = require('path');

pdfmake.setLocalAccessPolicy(() => true);
pdfmake.setUrlAccessPolicy(() => false);

const doc = pdfmake.createPdf({
  content: [
    { text: 'Annual Report 2024', style: 'heading' },
    'Contents go here...'
  ],
  styles: {
    heading: { fontSize: 20, bold: true }
  }
});

const outputPath = path.join(__dirname, 'output', 'annual-report.pdf');
await doc.write(outputPath);
console.log(`PDF saved to ${outputPath}`);

Browser Methods

The following methods are available only in the browser build (OutputDocumentBrowser). They rely on browser-specific APIs such as Blob, URL.createObjectURL, and the file-saver library.

getBlob()

Resolves with a Blob of type application/pdf containing the full PDF binary. Internally calls getBuffer() and wraps the result in new Blob([buffer], { type: 'application/pdf' }).
doc.getBlob()
// Returns: Promise<Blob>
import pdfmake from 'pdfmake/build/pdfmake';

const doc = pdfmake.createPdf({ content: 'Blob example' });

const blob = await doc.getBlob();
console.log(`Blob size: ${blob.size} bytes`);

// Upload to a server with FormData
const formData = new FormData();
formData.append('file', blob, 'document.pdf');
await fetch('/api/upload', { method: 'POST', body: formData });

download()

Triggers a browser file-save dialog using the file-saver library, offering the PDF as a download to the user.
doc.download(filename?)
// Returns: Promise<void>
filename
string
The suggested file name for the download. Defaults to 'file.pdf' if omitted.
import pdfmake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';

pdfmake.addVirtualFileSystem(pdfFonts);

document.getElementById('downloadBtn').addEventListener('click', async () => {
  const doc = pdfmake.createPdf({
    content: [
      { text: 'Receipt', style: 'header' },
      'Order #00421 — $49.99'
    ],
    styles: { header: { fontSize: 18, bold: true } }
  });

  await doc.download('receipt-00421.pdf');
});

open()

Opens the PDF in a new browser window or tab. pdfmake must open the window synchronously (before the async PDF generation begins) to avoid popup blockers, so it calls window.open() immediately and navigates the window to the blob URL once the PDF is ready.
doc.open(win?)
// Returns: Promise<void>
win
Window
An existing Window reference to navigate. If null or omitted, pdfmake opens a new window with window.open('', '_blank'). Pass a pre-opened window when you need to control the window before the PDF is ready.
If you do not pass a win reference, open() calls window.open() internally. Some browsers may block this as a popup if the call is not triggered by a direct user gesture. Always invoke open() from within a click or other user-event handler.
import pdfmake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';

pdfmake.addVirtualFileSystem(pdfFonts);

document.getElementById('previewBtn').addEventListener('click', () => {
  // Open the window synchronously inside the click handler
  const win = window.open('', '_blank');

  const doc = pdfmake.createPdf({ content: 'Preview this PDF!' });
  doc.open(win);
});

print()

Opens the PDF in a browser window and immediately triggers the browser’s native print dialog. Internally calls stream.setOpenActionAsPrint() on the PDFKit document to embed a print-on-open action, then delegates to open().
doc.print(win?)
// Returns: Promise<void>
win
Window
An existing Window reference, behaving identically to the win parameter of open(). If null or omitted, a new window is opened.
Like open(), print() calls window.open() when no win is provided. Call it from a user-initiated event to prevent popup blocking.
import pdfmake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';

pdfmake.addVirtualFileSystem(pdfFonts);

document.getElementById('printBtn').addEventListener('click', () => {
  const doc = pdfmake.createPdf({
    content: [
      { text: 'Print Preview', fontSize: 16, bold: true },
      'This PDF will open with the print dialog ready.'
    ]
  });

  doc.print();
});

Method Summary

MethodReturnsDescription
getStream()Promise<object>Raw PDFKit document stream
getBuffer()Promise<Buffer>Full PDF as a Node.js Buffer
getBase64()Promise<string>Full PDF as a base64 string
getDataUrl()Promise<string>Full PDF as a data: URL
write(filename)Promise<void>Write PDF to local file

Build docs developers (and LLMs) love