mpavlovic89
mpavlovic89

Reputation: 769

How to enable UTF-8 in jsPDF library

I am very happy to use jsPDF library which helps me to export my HTML page as PDF file. I came across some difficulties. I downloaded the library from http://parall.ax/products/jspdf/. When I use some characters like š, ć (UTF-8), in pdf they look like error. Even if I insert via doc.text. On the library's website, when I use their examples and change text using some of these characters - it works. So it is suppose to work with UTF-8. Why it isn't working on my computer.

I provide you my code. All missing here is the lib (which can be downloaded from the website) and you will see my problem. And why the CSS is dissapeared in pdf?

testing.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TESTING JSPDF LIB</title>
<script type="text/javascript" src="pdffile.js" charset="utf-8"></script>
<script type="text/javascript" src="jspdf/jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jspdf/jspdf.js"></script>
<script type="text/javascript" src="jspdf/libs/Deflate/adler32cs.js"></script>
<script type="text/javascript" src="jspdf/libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="jspdf/libs/Blob.js/BlobBuilder.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script>
<script>
function redirect() {
    document.write("Hello world" + '<br />');
}
</script>
</head>

<body>
<div id="box" class="box-shadow">
    <input type="submit" name="ok" id="ok" value="LETS TRY" onClick="redirect();pdf();" /> </div>
</div>
</body>
</html>

pdffile.js

function pdf() {
document.write('<div id="mydiv" style="background-color:#CCC; width:780px;640px;"><p>Open these letters š and c in PDF file and see error</p></div><br />');
document.write('<button id="export">OPEN IN PDF FILE</button>');

$(function () {
    var doc = new jsPDF();
    doc.text(35, 25, "Text with the letter Š");
    var specialElementHandlers = {
        'body': function (element, renderer) { 
            return true;
        }
    };
    $('#export').click(function () {
        doc.fromHTML($('#mydiv').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
});
}

Upvotes: 21

Views: 80540

Answers (5)

Soufiane ARBIB
Soufiane ARBIB

Reputation: 11

In jsPDF, The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports the wanted glyphs or else it will show garbled characters instead of the right text.

To add the font to jsPDF use our fontconverter in /fontconverter/fontconverter.html. The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.

Alternatively you can just load the content of the *.ttf file as a binary string using fetch or XMLHttpRequest and add the font to the PDF file:

const doc = new jsPDF();

const myFont = ... // load the *.ttf font file as binary string

// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");

Upvotes: 1

jsPDF still does not support UTF-8. Though it seems pdfmake.org supports UTF-8. Try using their playground and test it with your own characters.

Upvotes: 6

A.T Rayan
A.T Rayan

Reputation: 169

I have the answer after one day of searching throw all sites.

toPDF(): void {
    const AmiriRegular = 'AAEAAAASAQAABAAgRFNJR2D2zXQA.....A';

    const doc = new jsPDF({ filters: ["ASCIIHexEncode"] });

    doc.addFileToVFS("Amiri-Regular.ttf", AmiriRegular);
    doc.addFont("Amiri-Regular.ttf", "Amiri", "normal");

    doc.setFont("Amiri"); // set font
    doc.setFontSize(10);

    doc.text(10,10,'אוהב אותך'.split('').reverse().join(''));
       this.CAccounts.forEach(function (AccountsBody, i) {
      doc.text(20, 20 + (i * 10),


        "ID: " + AccountsBody.ID +
        "NAME: " + AccountsBody.NAME.split('').reverse().join(''));
    });
    doc.save('employee.pdf');

  }

Upvotes: 7

Asha Koshti
Asha Koshti

Reputation: 2993

jsPDF doesn't support UTF-8 Though the following plugin do make it possible as it integrates full custom font support when you can convert your file(FONT File) to BASE64.I have converted Arial Unicode to base64 and used it though it creates some spacing and alignment issues that you need to deal with by debugging into the code.

https://github.com/sphilee/jsPDF-CustomFonts-support

Upvotes: 2

beyondfloatingpoint
beyondfloatingpoint

Reputation: 1289

As of 2015, jsPDF doesn't support UTF-8 properly, workaround is to use html2canvas to render jpg or png and to add it to pdf. You can use following snippet to get an idea:

var doc = new jsPDF();

var utf_8_string_to_render = 'any_value_you_want';

Promise.all(
[
    new Promise(function (resolve) 
    {
        var temp = document.createElement("div");
        temp.id = "temp";
        temp.style = "color: black;margin:0px;font-size:20px;";
        phrase = utf_8_string_to_render;
        temp.innerHTML= phrase;
        //need to render element, otherwise it won't be displayed
        document.body.appendChild(temp);

        html2canvas($("#temp"), {
        onrendered: function(canvas) {

                $("#temp").remove();
            resolve(canvas.toDataURL('image/png'));
        },
        });
    })
]).then(function (ru_text) { 

    doc.addImage(ru_text[0], 'JPEG', 0,0);
    doc.text(0, 10, 'Non-utf-8-string' );

    doc.save('filename.pdf');
    });


};

Another libraries that do support utf-8 coding are:

  • PDFKit, which is reported to allow you to proper place your texts with coordinates.
  • PDFMake, which renders UTF-8 characters properly, but doesn't allow you to position text, except for styling it with margins.

Upvotes: 13

Related Questions