Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a utf-8 font to jsPDF library to print utf-8 Arabic pdfs in Angular application

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
like image 541
Ahmed Elkoussy Avatar asked Jul 11 '18 15:07

Ahmed Elkoussy


1 Answers

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

like image 54
Mahmoud Fawzy Avatar answered Nov 12 '22 13:11

Mahmoud Fawzy