I have been searching for hours to enable the UTF-8 support in jsPDF library, since it is a new feature released in jsPDF 1.4 I can't find useful resources to enable it
I found two methods in the library addFont()
& setFont()
but it is not clear in the official docs how to use them to use the new font & if they depend on each other
I am specifically trying to add a font that supports Arabic, like for example (Roboto) or any basic font that support Arabic
The code that I am using (& works well with English html but not Arabic):
printAsPDF() {
const elementToPrint = document.getElementById('report'); // The html element to become a pdf
const pdf = new jsPDF();
pdf.setFont('Helvetica');
console.log(pdf.getFontList());
pdf.fromHTML(elementToPrint, 30, 30);
pdf.save('hello.pdf');
}
The fonts that are supported by default:(output of getFontList()
):
Courier
Helvetica
Symbol
Times
ZapfDingbats
courier
helvetica
symbol
times
zapfdingbats
first the bad news: fromHTML is deprecated so try not to use it.
you can use it by setting an arabic font and decoding it to Base64 like this:
const AmiriRegular = environment.AmiriRegular.trim();
doc.addFileToVFS('Amiri-Regular.ttf', AmiriRegular);
doc.addFont('Amiri-Regular.ttf', 'Amiri', 'normal');
doc.setFont('Amiri'); // set font
doc.setFontSize(20);
doc.text('مرحبا', 200, 10, { align: 'right', lang: 'ar' });
// Save the PDF
doc.save('Test.pdf');
the AmiriRegular const here is the base64 value for the amiri font and you can decode fonts here:
fonts decoder
good news: you can use html2pdf instead by running the command
=> npm install html2pdf
then calling the html2pdf function with or without setting the options for the page, then saving the file by calling save function here is an example:
const content = `<h1>صلي علي سيدنا محمد صلي الله عليه وسلم</h1>`;
const opt = {
margin: 1,
filename: 'Test.pdf',
image: { type: 'jpeg', quality: 1 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// Save the PDF
html2pdf().set(opt).from(content).save();
but remember that html2pdf is generating an image for the html content not like fromhtml function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With