JavaScript pdf generation library with Unicode support

Sumeet picture Sumeet · Jul 13, 2016 · Viewed 7.5k times · Source

I want to generate a pdf file using JavaScript at client side . Firstly I tried using jsPdf API . But it does not work with Unicode character like Chinese.

Is there any option to enhance jspdf to support Unicode or any other library which supports Unicode .

Pdfmake API says it supports Unicode but when I tried it also does not work out, I checked in there demo example placing Unicode character .

I tried using pdfkit in Node.js but pdf is not getting created properly

var PDFDocument = require("pdfkit");
var fs = require('fs');

var doc = new PDFDocument;

doc.pipe(fs.createWriteStream('output.pdf'));

doc.fontSize(15);
doc.text('Generate PDF! 漢字漢字漢字漢字');

doc.end();

In pdf it created as Generate PDF! o"[Wo"[Wo"[Wo"[W

Also , Can I add multiple font in pdfMake

 var fontDescriptors = {
    Roboto: {
      normal: 'examples/fonts/Roboto-Regular.ttf',
      bold: 'examples/fonts/Roboto-Medium.ttf',
      italics: 'examples/fonts/Roboto-Italic.ttf',
      bolditalics: 'examples/fonts/Roboto-Italic.ttf'
    }
  };

  var printer = new pdfMakePrinter(fontDescriptors);

Answer

HiDeo picture HiDeo · Jul 18, 2016

I'll describe a solution using Node.js and PDFKit since you mentioned it but it also applies to pdfmake which internally uses PDFKit.

Most of the time, the default font used in these libraries do not accept Chinese characters. You have to add and use fonts that are compatible for the languages you need to support. If we take pdfmake for example, they use Roboto as their default font and it indeed does not accept Chinese characters.

Using your code example, we can add support for Chinese using the Microsoft YaHei font (msyh.ttf) for instance with only 1 additional line of code:

var PDFDocument = require("pdfkit");
var fs = require('fs');

var doc = new PDFDocument;

doc.pipe(fs.createWriteStream('output.pdf'));

doc.font('fonts/msyh.ttf');
doc.fontSize(15);
doc.text('Generate PDF! 漢字漢字漢字漢字');

doc.end();

The output would look like this:

PDF Output