'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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|