Generation of PDF from HTML with non-Latin characters using ITextRenderer does not work

喜你入骨 提交于 2019-12-03 12:15:13
ArcanisCz

i am from Czech Republic, and had same problem with our national symbols! After some searching, i managed to solve it with this solution.

Specifically with (which you already have):

renderer
    .getFontResolver()
    .addFont(fonts.get(i).getFile().getPath(), 
             BaseFont.IDENTITY_H, 
             BaseFont.NOT_EMBEDDED);

and then important part in CSS:

* {
  font-family: Verdana;
/*  font-family: Times New Roman; - alternative. Without ""! */
}

It seems to me, without that css, your fonts are not used. When i remove theese lines from CSS, encoding is broken again.

Hope this will help!

Add to your HTML something like this:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
        <style type='text/css'> 
            * { font-family: 'Arial Unicode MS'; }
        </style>
    </head>
    <body>
        <span>Some text with šđčćž characters</span>
    </body>
</html>

and then add FontResolver to ITextRenderer in java code:

ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("fonts/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

works great for Croatian characters

jars used for generating PDF are:

core-renderer.jar
iText-2.0.8.jar

Let the iText read a header info from your html content that it contains utf-8 content.
Add meta tag for content-type in html code with utf-8 charset encoding then run iText to generate PDF and check the result.

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 </head>
 <body>
  Some greek characters: Καλημέρα Some greek characters
 </body>
</html>

Update:
If the above is not working, then refer to ENCODING VERSUS THE DEFAULT CHARSET USED BY THE JVM in the document published at http://www.manning.com/lowagie2/iText2E_MEAP_CH02.pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!