Search code examples
jspdf

Setting styles for embedded fonts in jsPDF


i have an issue with generating pdfs in regards to embedding fonts. I just used

pdf.addFileToVFS('Acme-Regular-italic.ttf', fontBase64Data);
pdf.addFont('Acme-Regular-italic.ttf', 'Acme', 'italic');
pdf.setFont("Acme", 'italic');
pdf.text("italic Acme", 10, 10);

pdf.addFileToVFS('Acme-Regular.ttf', fontBase64Data);
pdf.addFont('Acme-Regular.ttf', 'Acme', 'normal');
pdf.setFont("Acme", 'normal');
pdf.text("regular Acme", 10, 40);

pdf.addFileToVFS('Acme-Regular-bold.ttf', fontBase64Data);
pdf.addFont('Acme-Regular-bold.ttf', 'Acme', 'bold');
pdf.setFont("Acme", 'bold');
pdf.text("bold Acme", 10, 70);

where fontBase64Data is always the Acme.ttf encodes as base64

and the font i see for the three variants is always the same!? So I wonder what I am missing. Do I need to pass different base64 encodingds (one for regular, one for bold...) - whcih I don't have? If so where can I get those?

Here the result i get as screenshot from pdf: enter image description here

Cheers Tom


Solution

  • Base64 is one input file one output file so if its built from command

    base64 -e upright.ttf fontBase64.Data
    

    then on decoding that string it can only be one single upright.ttf

    For each family style you wish to embed you will need separate font ttfs

    • normal.ttf
    • italic.ttf
    • bold.ttf
    • bold italic.ttf

    the preferred method is supply the regular/normal.ttf italic/oblique.ttf and bold/heavy.ttf etc. to the converter per the web site method enter image description here https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html

    but do read the instructions at https://github.com/parallax/jsPDF#use-of-unicode-characters--utf-8

    in return you will get the base64 style in a js wrapper enter image description here

    one advantage of holding the data in a referenced fontstyle.js is that the decompressed ttfs do not need to be included inline on the pdf building html page just linked like any other resource.