jsPDF: .html method can't handle Chinese correctly, even after used the .setFont method.

Hello, I’m using jsPDF 1.5.3 version, but I found Chinese doesn’t display correctly when I use .html method. But it will work when I use the .text method. This makes me confused. So, does there any solutions, for trans a Chinese HTML page to PDF with using the awesome jsPDF? I will be very grateful for this 😊.

Here are my scripts:( I’m using SourceHanSansCN.ttf for Chinese, you can find it from here: Source-Han-TrueType )

<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js'></script>
<script src="./js/SourceHanSansCN-Normal-normal.js"></script>

Here is my javascript code:

var doc = new jsPDF({ orientation: 'p', format: 'a4'  });
doc.setFont( 'SourceHanSansCN-Normal', 'normal' );
doc.html( '<div>Chinese: 中文</div>' , {
    callback: function ( newDoc ) {
        newDoc.save( 'chinese-html.pdf' )
    }
});

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 25

Most upvoted comments

ok my last post had the html-markup parsed

So you should have to do something like <div style="font-family: SourceHanSansCN-Normal">中文<div>

How does .html know that it should use that chinese font?

So you should have to do something like <div style="font-family: SourceHanSansCN-Normal">chinese stuff<div>

I found a way to render custom font. Set font to element before .html function, it can correct rendering. The process of adding fonts is omitted here.

Ele.style.fontFamily = "simhei"
let PDF = new jsPDF('', 'pt', 'a4')
PDF.setFont("simhei");
PDF.html(Ele, ...)

@Saggv , .setFont( ) works with.text( ) , as you already know

.html is another method, so to set the font do the following

<div style="font-family: 'write your font name here' ">something in japanese<div>

This solution has already been mentioned 😃 , kudos

if doc.setFont(‘fontname’) works then setting font-family:‘fontname’ should work as well. As mentioned earlier by @FaustYKKN you should use lowercase letters while naming your fonts