Search code examples
jspdf

How can I use a custom font in jsPDF?


I know, this question has been asked e. g. here and here but whatever I try, I do not get my custom font in the generated pdf. Here are my steps:

  • Download ttf from here.
  • As described in the official readme, convert ttf to js here.
  • Add the js file to wwwroot folder.
  • Add the following code in index.html <body>:
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
<script src="./SourceSansPro-Regular-normal.js" type="module"></script>
  • Add create-pdf.js with following code to wwwroot folder:
export function generateAndDownloadPdf() {
    const doc = new jspdf.jsPDF({
        orientation: 'p',
        unit: 'pt',
        format: 'a4',
        putOnlyUsedFonts: true
    });
    doc.setFont("SourceSansPro-Regular", "normal");
    doc.text(50, 50, 'Hello world');
    doc.save("sample.pdf");
}
  • In Index.razor add
@inject IJSRuntime JSRuntime
<button class="btn btn-primary" @onclick="DownloadPdf">pdf</button>

@code {
    private async Task DownloadPdf()
    {
        await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./create-pdf.js");
        await module.InvokeVoidAsync("generateAndDownloadPdf");
    }
}
  • Run app, click button and observe that the font is not Source Sans Pro.

What am I doing wrong?


Solution

  • To get the custom font, follow the steps in the question and do the following:

    index.html

    Delete type="module"

    <script src="./SourceSansPro-Regular-normal.js"></script>
    

    SourceSansPro-Regular-normal.js

    Modify to the following. (Do not forget to delete the line `import { jsPDF } from "jspdf"`)
    var font = 'AAE...';
    var callAddFont = function () {
        this.addFileToVFS('SourceSansPro-Regular-normal.ttf', font);
        this.addFont('SourceSansPro-Regular-normal.ttf', 'SourceSansPro-Regular', 'normal');
    };
    jspdf.jsPDF.API.events.push(['addFonts', callAddFont])
    

    Edit

    If you want to add more than 1 custom font, modify the font js files as follows
    (function () {
        var font = 'AAE...';
        var callAddFont = function () {
            this.addFileToVFS('SourceSansPro-Regular-normal.ttf', font);
            this.addFont('SourceSansPro-Regular-normal.ttf', 'SourceSansPro-Regular', 'normal');
        };
        jspdf.jsPDF.API.events.push(['addFonts', callAddFont])
    })();
    

    If you do not add the first and last line, the font will always be the last one, you added in index.html