BasePdfDoc
import BasePdfDoc, { applyDefaultPDFOptions, parseParams } from '@bbc/front-end-kit/js/pdf/core/BasePdfDoc';
Provides a base class to extend from for a simplified way of generating PDFs in JavaScript. Extends PDFKit's PDFDocument, adding asset loading via AssetLoader and PDF generation to Blob or Object URL via blob-stream.
Getting started
import BasePdfDoc from '@bbc/front-end-kit/js/pdf/core/BasePdfDoc';
const myPdf = new BasePdfDoc();
myPdf
.addPage()
.fontSize(25)
.text('My first PDF document', 100, 100);
// generate as Blob
const pdfBlob = await myPdf.generate({ type: 'blob' });
// generate as Object URL
const pdfUrl = await myPdf.generate({ type: 'url' });
It is recommended to extend BasePdfDoc per document type so the template can be reused across the project:
class MyPdf extends BasePdfDoc {
constructor(args = {}) {
super(args);
this.content = args.content;
}
async generate(args) {
this
.addPage()
.fontSize(25)
.text(this.content.title, 100, 100);
return super.generate(args);
}
}
const pdf = new MyPdf({ content: { title: 'Hello World' } });
const blob = await pdf.generate({ type: 'blob' });
Tips
BasePdfDoc can be extended multiple layers deep. A common pattern is a project-level template class (e.g. BBCPdf) that loads shared fonts and images in init(), and then document-specific classes (e.g. OfferPdf) that extend it further.
API
constructor(...args)
Initialises the BasePdfDoc instance. All arguments are forwarded to PDFDocument. Also pipes the PDFKit stream through blob-stream and creates an internal AssetLoader instance.
See PDFKit getting started for supported constructor options.
Methods
init()
Empty hook method — override in subclasses to load fonts/images or perform other async setup before rendering. Not called automatically by the constructor; call it yourself before generating.
generate(args)
Calls PDFDocument.end() and waits for the stream to finish, then resolves with the requested output type.
Parameters
args(object):type(string): Output format —'blob'(returns aBlob) or'url'(returns a blob Object URL string).
Returns
Promise<Blob|string> — resolves with the generated PDF as a Blob or Object URL.
Getters & Setters
assetLoader
Returns the internal AssetLoader instance (_assetLoader). Use it to load fonts and images before rendering.
Exported utility functions
applyDefaultPDFOptions(args, defaults)
Merges defaults into the last element of the args array using defaultsDeep. Used internally to apply default PDFKit constructor options.
parseParams(x, options)
Mirrors PDFKit's image mixin logic: if x is an object, treats it as options and sets x = null. Returns the resolved options object.
External dependencies
- PDFKit (
pdfkit/js/pdfkit.standalone.js): PDF generation engine. - blob-stream: Converts the PDFKit stream to a Blob or Object URL.
- lodash-es
defaultsDeep: Used inapplyDefaultPDFOptions. AssetLoader: Internal asset loading and caching.