Text in PDFKit

The basics

PDFKit makes adding text to documents quite simple, and includes many options to customize the display of the output. Adding text to a document is as simple as calling the text method.

doc.text('Hello world!')

Internally, PDFKit keeps track of the current X and Y position of text as it is added to the document. This way, subsequent calls to the text method will automatically appear as new lines below the previous line. However, you can modify the position of text by passing X and Y coordinates to the text method after the text itself.

doc.text('Hello world!', 100, 100)

If you want to move down or up by lines, just call the moveDown or moveUp method with the number of lines you'd like to move (1 by default).

Line wrapping and justification

PDFKit includes support for line wrapping out of the box! If no options are given, text is automatically wrapped within the page margins and placed in the document flow below any previous text, or at the top of the page. PDFKit automatically inserts new pages as necessary so you don't have to worry about doing that for long pieces of text. PDFKit can also automatically wrap text into multiple columns.

The text will automatically wrap unless you set the lineBreak option to false. A line can break wherever the Unicode line-breaking rules allow, including after a hyphen or slash. Set lineBreak to 'whitespace' to keep words such as design-system or URLs together when they fit on a line. This mode still allows breaks at whitespace, soft hyphens and zero-width spaces; words too wide for a line are still split. By default it will wrap to the page margin, but the width option allows you to set a different width the text should be wrapped to. If you set the height option, the text will be clipped to the number of lines that can fit in that height.

When line wrapping is enabled, you can choose a text justification. There are four options: left (the default), center, right, and justify. They work just as they do in your favorite word processor, but here is an example showing their use in a text box.

const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus.  Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl.';

doc.fontSize(8);
doc.text(`This text is left aligned. ${lorem}`, {
  width: 410,
  align: 'left'
}
);

doc.moveDown();
doc.text(`This text is centered. ${lorem}`, {
  width: 410,
  align: 'center'
}
);

doc.moveDown();
doc.text(`This text is right aligned. ${lorem}`, {
  width: 410,
  align: 'right'
}
);

doc.moveDown();
doc.text(`This text is justified. ${lorem}`, {
  width: 410,
  align: 'justify'
}
);

// draw bounding rectangle
doc.rect(doc.x, 0, 410, doc.y).stroke();

The output of this example, looks like this:

Output of example 2

Text styling

PDFKit has many options for controlling the look of text added to PDF documents, which can be passed to the text method. They are enumerated below.

Additionally, the fill and stroke color and opacity methods described in the vector graphics section are applied to text content as well.


Here is an example combining some of the options above, wrapping a piece of text into three columns, in a specified width and height.

const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';

doc.text(lorem, {
  columns: 3,
  columnGap: 15,
  height: 100,
  width: 465,
  align: 'justify'
});

The output looks like this:

Output of example 3

Text measurements

If you're working with documents that require precise layout, you may need to know the size of a piece of text. PDFKit has three methods to achieve this: widthOfString(text, options) , heightOfString(text, options) and boundsOfString(text, options)/boundsOfString(text, x, y, options). All methods use the same options described in the Text styling section, and take into account the eventual line wrapping.

However boundsOfString factors in text rotations and multi-line wrapped text, effectively producing the bounding box of the text, {x: number, y: number, width: number, height: number}. If x and y are not defined they will default to use this.x and this.y.

Lists

The list method creates a bulleted list. It accepts as arguments an array of strings, and the optional x, y position. You can create complex multilevel lists by using nested arrays. Lists use the following additional options:

Rich Text

As mentioned above, PDFKit supports a simple form of rich text via the continued option. When set to true, PDFKit will retain the text wrapping state between text calls. This way, when you call text again after changing the text styles, the wrapping will continue right where it left off.

The options given to the first text call are also retained for subsequent calls after a continued one, but of course you can override them. In the following example, the width option from the first text call is retained by the second call.

doc.fillColor('green')
   .text(lorem.slice(0, 500), {
     width: 465,
     continued: true
   }).fillColor('red')
   .text(lorem.slice(500));

Here is the output:

Output of example 4

To cancel a link in rich text set the link option to null.

doc.fillColor('red')
   .text(lorem.slice(0, 199), {
     width: 465,
     continued: true
   })
   .fillColor('blue')
   .text(lorem.slice(199, 282), {
     link: 'http://www.example.com',
     continued: true
   })
   .fillColor('green')
   .text(lorem.slice(182, 400), {
     link: null
   });

Here is the output:

Output of example 5

With continued text, center and right alignment apply to each segment rather than to the line as a whole, so segments can overlap.

Fonts

This fork embeds fonts from memory instead of shipping the 14 standard PDF fonts or reading font files from disk. It supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collection (.ttc), and Datafork TrueType (.dfont) fonts.

Supply a name in options.font and the default font data in options.fontData when creating a document. To change fonts, call doc.font() with a Uint8Array, an ArrayBuffer, or an already-parsed fontkit font instance. For collection bytes, pass the PostScript name of the desired face as the second argument (or set options.fontFamily for the default font).

const goodDog = await fetch('/fonts/GoodDog.ttf').then(res => res.arrayBuffer());
const doc = new PDFDocument({ font: 'Body', fontData: goodDog });
doc.fontSize(18).text('This is Good Dog!');

const chalkboard = await fetch('/fonts/Chalkboard.ttc').then(res => res.arrayBuffer());
doc.font(chalkboard, 'Chalkboard-Bold').text('This is Chalkboard.');

Use registerFont() to give an in-memory font source a reusable alias:

doc.registerFont('Heading', chalkboard, 'Chalkboard-Bold');
doc.font('Heading').text('This is a heading.');

That's about all there is too it for text in PDFKit. Let's move on now to images.