How to change Font style and font family in PDF-Lib NodeJS for only one text Field

1.2k Views Asked by At

I am trying to change the font style and font family for the signature field in my PDF using PDF-Lib library in nodejs.Here is my code , but I am unable to change the font.

const {PDFDocument, degrees, rgb, StandardFonts} = require('pdf-lib');

const fontKit = require('@pdf-lib/fontkit');
const fs = require('fs');
var fontkit = require('fontkit');

const pdfDoc = await PDFDocument.load(await readFile('pdf24_merged.pdf'));
pdfDoc.registerFontkit(fontkit);

const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRomanBoldItalic)

const signature = form.getTextField('Datum und Unterschrift');
signature.setFontSize(25);
signature.setText(str);
signature.updateAppearances(timesRomanFont);
signature.defaultUpdateAppearances(timesRomanFont);
console.log(str);

I have tried one of the answers on stackoverflow but didn't work out for me.Can some suggest me changes so that I can change the font family and style to italics so that my signature field looks different from text on the rest of the fields?

2

There are 2 best solutions below

1
On

I suspect that the actual font loading might not be working as expected since you're trying to use 'TimesRomanBoldItalic' which isn't one of the standard fonts offered by PDF-Lib. The available standard ones include TimesRoman, Helvetica , and Courier in various forms (normal, bold, italic, and bold italic).

But hey, don't sweat it. If you need to use a specific custom font style , you can always load it from a .ttf or .otf file like so:

const customFontBytes = fs.readFileSync('path_to_your_font.ttf');
const customFont = await pdfDoc.embedFont(customFontBytes);

Now you can set your font to the signature field:

const signature = form.getTextField('Datum und Unterschrift');
signature.setFontSize(25);
signature.setText(str);
signature.updateAppearances(customFont);
signature.defaultUpdateAppearances(customFont);
Voila! Now your signature should have the style you want. Please ensure that your 'path_to_your_font.ttf' is correctly pointed to the location of your .ttf or .otf file.

Don't forget to save your changes:

const pdfBytes = await pdfDoc.save();
fs.writeFileSync('path_to_output.pdf' , pdfBytes);
0
On

I was using the vscode-pdf extension to view changes to my PDF. This extension has some issues that It was not showing the italics font-style in my PDF. My code was working well. After spending 16-18h, I came to know about this. If anyone else is facing the same issue, I would recommend opening the changed PDF in the Google Chrome or any other PDF viewer so that one can verify his changing.