I am trying to convert my HTML content to a PDF using the jsPDF library. The HTML file contains custom fonts that are defined using @font-face with Base64-encoded font URLs. However, when I generate the PDF, the fonts are not applied, and the PDF appears to use a default fallback font.
Here is an example of my code: index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Custom Font PDF</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
@font-face {
font-family: 'LSTCNP+Noto Serif Bold';
src: url('data:font/woff2;charset=utf-8;base64,d09xxaxadfdfdfdfGMg...cAAA==')
format('woff2');
}
@font-face {
font-family: 'GLQUUO+Noto Serif';
src: url('data:application/octet-stream;base64,AAEAAAANAIAAAwBQ..AA=') format('truetype');
}
.custom-font-bold {
font-family: 'LSTCNP+Noto Serif Bold';
font-size: 20px;
color: #333333;
}
.custom-font-regular {
font-family: 'GLQUUO+Noto Serif';
font-size: 16px;
color: #555555;
}
</style>
</head>
<body>
<button onclick="convertToPDF()">Generate PDF</button>
<div id="contentToPrint">
<p class="custom-font-bold">This is using the Bold Custom Font</p>
<p class="custom-font-regular">This is using the Regular Custom Font</p>
</div>
<script>
const { jsPDF } = window.jspdf;
function convertToPDF() {
const doc = new jsPDF();
const elementHTML = document.querySelector("#contentToPrint");
doc.html(elementHTML, {
callback: function (doc) {
doc.save("custom-font.pdf");
},
margin: [10, 10, 10, 10],
html2canvas: {
scale: 0.8, // Adjust scaling factor if needed
},
x: 10,
y: 10,
});
}
</script>
</body>
</html>
Problem:
The fonts render correctly when I open the HTML in a browser.
What I have tried:
Used both .woff2 and .ttf fonts in the @font-face rule.
Verified the Base64 encoding of the fonts.
Tried adjusting html2canvas settings (scale, windowWidth). However, when I generate the PDF using jsPDF, the custom fonts are not applied, and it falls back to the default system font.
here is my stackblitz link
How can I make jsPDF pick up the custom fonts defined in the HTML? Is there something I am missing?
Thank you in advance!
