From the specs https://www.npmjs.com/package/pdf-lib#embed-font-and-measure-text

pdf-lib relies on a sister module to support embedding custom fonts: @pdf-lib/fontkit. You must add the @pdf-lib/fontkit module to your project and register it using pdfDoc.registerFontkit(...) before embedding custom fonts.

We have to npm i --save @pdf-lib/fontkit and we have to have source from where which we will read the font. In my case I have added .otf file in project and loaded font. Files are structured like on the image:

import path from 'path';
import fs from 'fs';
import {PDFDocument, PDFForm, StandardFonts, PDFFont} from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';

const pdfBytes = fs.readFileSync(path.join(__dirname, `/w_template/` + fileName + '.pdf'));
const pdfDoc = await PDFDocument.load(pdfBytes);

pdfDoc.registerFontkit(fontkit);
//load font and embed it to pdf document
const fontBytes = fs.readFileSync(path.join(__dirname, 'HouschkaHead-BoldItalic.otf'));
const customFont = await pdfDoc.embedFont(fontBytes);

const form = pdfDoc.getForm();
const textField = form.getTextField('signature');
textField.setFontSize(11);
textField.setText('stefan z');
textField.updateAppearances(customFont);

// form flatten is available from v1.16.0 and it makes form read-only (not editable)
form.flatten();
const modifiedPdf = await pdfDoc.save();

And this is the final result: check how the signature input form field is different from rest of input fields which are filled with default font Bonus: if you want to play with color of the text of inputs in form, this is what I have found while digging more under the library source code (it might be not optimal, but it can give you starting point for more things):

import {setFillingRgbColor} from 'pdf-lib'

const textField = form.getTextField(fieldName);
const da = textField.acroField.getDefaultAppearance() ?? '';
const newDa = da + '\n' + setFillingRgbColor(1, 0, 0).toString(); 
textField.acroField.setDefaultAppearance(newDa);

Answer from Stefan on Stack Overflow
🌐
PDF-LIB
pdf-lib.js.org › docs › api › enums › standardfonts
StandardFonts · PDF-LIB
pdf-lib › StandardFonts · Courier · CourierBold · CourierBoldOblique · CourierOblique · Helvetica · HelveticaBold · HelveticaBoldOblique · HelveticaOblique · Symbol · TimesRoman · TimesRomanBold · TimesRomanBoldItalic · TimesRomanItalic · ZapfDingbats ·
🌐
npm
npmjs.com › package › @pdf-lib › standard-fonts
pdf-lib/standard-fonts
Metrics for the Standard 14 PDF fonts and their encodings. Latest version: 1.0.0, last published: 5 years ago. Start using @pdf-lib/standard-fonts in your project by running `npm i @pdf-lib/standard-fonts`. There are 66 other projects in the npm registry using @pdf-lib/standard-fonts.
      » npm install @pdf-lib/standard-fonts
    
Published   Sep 13, 2020
Version   1.0.0
Author   Andrew Dillon
Top answer
1 of 3
22

From the specs https://www.npmjs.com/package/pdf-lib#embed-font-and-measure-text

pdf-lib relies on a sister module to support embedding custom fonts: @pdf-lib/fontkit. You must add the @pdf-lib/fontkit module to your project and register it using pdfDoc.registerFontkit(...) before embedding custom fonts.

We have to npm i --save @pdf-lib/fontkit and we have to have source from where which we will read the font. In my case I have added .otf file in project and loaded font. Files are structured like on the image:

import path from 'path';
import fs from 'fs';
import {PDFDocument, PDFForm, StandardFonts, PDFFont} from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';

const pdfBytes = fs.readFileSync(path.join(__dirname, `/w_template/` + fileName + '.pdf'));
const pdfDoc = await PDFDocument.load(pdfBytes);

pdfDoc.registerFontkit(fontkit);
//load font and embed it to pdf document
const fontBytes = fs.readFileSync(path.join(__dirname, 'HouschkaHead-BoldItalic.otf'));
const customFont = await pdfDoc.embedFont(fontBytes);

const form = pdfDoc.getForm();
const textField = form.getTextField('signature');
textField.setFontSize(11);
textField.setText('stefan z');
textField.updateAppearances(customFont);

// form flatten is available from v1.16.0 and it makes form read-only (not editable)
form.flatten();
const modifiedPdf = await pdfDoc.save();

And this is the final result: check how the signature input form field is different from rest of input fields which are filled with default font Bonus: if you want to play with color of the text of inputs in form, this is what I have found while digging more under the library source code (it might be not optimal, but it can give you starting point for more things):

import {setFillingRgbColor} from 'pdf-lib'

const textField = form.getTextField(fieldName);
const da = textField.acroField.getDefaultAppearance() ?? '';
const newDa = da + '\n' + setFillingRgbColor(1, 0, 0).toString(); 
textField.acroField.setDefaultAppearance(newDa);

2 of 3
7

If anyone is struggling to change the fontSize in filling text fields using the latest inbuilt function called setFontSize(). You can use this approach.

const { PDFDocument, setFontAndSize } = require('pdf-lib');

   const pdfDoc = await PDFDocument.load(file);
   const form = pdfDoc.getForm();

const textField = form.getTextField('106Mobile.1');
    textField.setText('This works fine');
    const da = textField.acroField.getDefaultAppearance() ?? '';
    const newDa = da + '\n' + setFontAndSize('Courier', 8).toString(); //setFontAndSize() method came to resuce
    textField.acroField.setDefaultAppearance(newDa);

I had to use this because I got an error saying

No /DA (default appearance) entry found for field: 106Title.1

when setting font sizes to some text fields (not all of it). But I degenerately had those text fields. Fixed it using the above workaround.

🌐
PDF-LIB
pdf-lib.js.org › docs › api › classes › pdffont
PDFFont · PDF-LIB
Represents a font that has been embedded in a PDFDocument.
🌐
GitHub
github.com › Hopding › pdf-lib › issues › 468
Standard Fonts are NOT actually embedded · Issue #468 · Hopding/pdf-lib
June 1, 2020 - When I try to embed a standard font from an external link - such as an S3 bucket I put them in, or something - it names it something like "Helvetica-3368" which means the text that references "Helvetica" doesn't use it. What would you recommend? Is there a flag I'm missing to force an embed? Here's a small excerpt of the code I'm trying to use: var tempPDF = await PDFDocument.load(event.base64pdf); console.log(fontkit); await tempPDF.registerFontkit(fontkit); for (var font of ["Courier", "CourierBold", "CourierOblique", "CourierBoldOblique", "Helvetica", "HelveticaBold", "HelveticaOblique", "HelveticaBoldOblique", "TimesRoman", "TimesRomanBold", "TimesRomanItalic", "TimesRomanBoldItalic", "Symbol", "ZapfDingbats"] ) { await tempPDF.embedFont(StandardFonts[font]); } var tempStr = await tempPDF.saveAsBase64({dataUri: false});
Published   Jun 01, 2020
🌐
npm
npmjs.com › package › pdf-lib
pdf-lib - npm
Tests 1, 14, 15, 16, and 17 in ... to display text in buttons, dropdowns, option lists, and text fields is the standard Helvetica font....
      » npm install pdf-lib
    
Published   Nov 06, 2021
Version   1.17.1
Author   Andrew Dillon
🌐
CodeSandbox
codesandbox.io › examples › package › @pdf-lib › standard-fonts
pdf-lib/standard-fonts examples
Use this online @pdf-lib/standard-fonts playground to view and fork @pdf-lib/standard-fonts example apps and templates on CodeSandbox.
🌐
PDFlib
pdflib.com › pdflib-cookbook › fonts
fonts
PDFlib GmbH(Powered by Apryse, Producer of the Market's Leading PDF SDK)
🌐
PDFlib
pdflib.com › pdflib-cookbook › fonts › font-info
font-info
Query various properties of a font such as font name, font style, or encoding · Download Java Code Switch to PHP Code Show Output
Find elsewhere
🌐
JSFiddle
jsfiddle.net › Hopding › rgu6ca59 › 2
Embed Font and Measure Text (pdf-lib) - JSFiddle - Code Playground
You can now use different monospace fonts in the editor − we now have a curated list of pretty awesome fonts available including premium ones. Just open the Coder Fonts mini-app from the sidebar or from Editor settings.
🌐
PDF-LIB
pdf-lib.js.org
PDF-LIB · Create and modify PDF documents in any JavaScript environment.
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib' async function createPdf() { const pdfDoc = await PDFDocument.create() const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman) const page = pdfDoc.addPage() const { width, height } = page.getSize() const fontSize = 30 page.drawText('Creating PDFs in JavaScript is awesome!', { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }) const pdfBytes = await pdfDoc.save() }
🌐
GitHub
github.com › Hopding › pdf-lib › blob › master › README.md
pdf-lib/README.md at master · Hopding/pdf-lib
Tests 1, 14, 15, 16, and 17 in ... to display text in buttons, dropdowns, option lists, and text fields is the standard Helvetica font....
Author   Hopding
🌐
GitHub
github.com › Hopding › pdf-lib
GitHub - Hopding/pdf-lib: Create and modify PDF documents in any JavaScript environment
Tests 1, 14, 15, 16, and 17 in ... to display text in buttons, dropdowns, option lists, and text fields is the standard Helvetica font....
Starred by 8.1K users
Forked by 829 users
Languages   TypeScript 80.9% | HTML 9.9% | JavaScript 8.5% | Objective-C 0.3% | CSS 0.2% | Starlark 0.1% | Java 0.1%
🌐
GitHub
github.com › Hopding › standard-fonts
GitHub - Hopding/standard-fonts: Collection of metrics and encodings for the standard 14 PDF fonts
Collection of metrics and encodings for the standard 14 PDF fonts · This project is a fork of afm and was created for use in pdf-lib.
Starred by 2 users
Forked by 6 users
Languages   TypeScript 84.2% | JavaScript 12.7% | HTML 3.1%
🌐
UNPKG
unpkg.com › browse › [email protected] › README.md
pdf-lib
You can use a standard font like so: <!-- prettier-ignore --> ```js import { PDFDocument, StandardFonts } from 'pdf-lib' const pdfDoc = await PDFDocument.create() const courierFont = await pdfDoc.embedFont(StandardFonts.Courier) const page = pdfDoc.addPage() page.drawText('Some boring latin text in the Courier font', { font: courierFont, }) ``` - **The standard fonts do not support all characters** available in Unicode.
🌐
UNPKG
app.unpkg.com › @pdf-lib › [email protected]
UNPKG
Metrics for the Standard 14 PDF fonts and their encodings · github.com/Hopding/standard-fonts · Hopding/standard-fonts · 3 folders, 3 files · Hopding/standard-fonts · Latest: 1.0.0 ·
🌐
PDFlib
pdflib.com › pdflib-cookbook › fonts › font_info
fonts/font_info
Query various properties of a font such as font name, font style, or encoding · Download Java Code Switch to PHP Code Show Output
🌐
Stack Exchange
salesforce.stackexchange.com › questions › 393881 › problem-with-adding-custome-font-and-pdf-lib
lightning web components - problem with adding custome font and pdf-lib - Salesforce Stack Exchange
async createPdf() { const pdfDoc = await PDFLib.PDFDocument.create(); const timesRomanFont = await pdfDoc.embedFont(PDFLib.StandardFonts.TimesRoman); const page = pdfDoc.addPage(); const { width, height } = page.getSize(); const fontSize = 30; page.drawText("Learning with Salesforce Bolt !", { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: PDFLib.rgb(0, 0.53, 0.71) }); const pdfBytes = await pdfDoc.save(); const stampedPDF = await pdfDoc.save(); const tempblob = new Blob([stampedPDF], { type: "application/pdf" }); this.showPDF = URL.createObjectURL(tempblob); } .
🌐
PDFlib
pdflib.com › pdflib-cookbook › fonts › font_configuration
fonts/font_configuration
In this case no prerequisites * are required provided that you know the exact (case-sensitive) * name of the font (see the PDFlib Tutorial for information about * how to retrieve the exact name of a host font). For example, if * you installed the font "Verdana" in the system you can load it ...
🌐
PDFlib
pdflib.com › pdflib-cookbook › fonts › starter-fallback
starter-fallback - Fonts
"{fontname=EmojiOneColor colormode=ignoremono}", // U+1F602 = Face with Tears of Joy // Use PDFlib syntax for numerical glyph references since // Java doesn't support U+XXXXX syntax for characters beyond U+FFFF "Emoji: &#x1F602;"), new testcase( "Add enlarged pictogram", "NotoSerif-Regular", // U+261E = WHITE RIGHT POINTING INDEX "{fontname=ZapfDingbats forcechars=U+261E fontsize=150% textrise=-15%}", "hand symbol: \u261E"), new testcase( "Add enlarged symbol glyph", "NotoSerif-Regular", // U+2663 = Black Club Suit "{fontname=Symbol forcechars=U+2663 fontsize=125%}", "club symbol: \u2663"), ne