HTML to PDF using custom font (Identity-H)

时间:2016-04-25 09:27:00

标签: itext flying-saucer

I'm using Flying Saucer 9.0.9 (it's the same on 9.0.8) and I'm getting strange behaviour when using a custom font using the "IDENTITY-H" encoding. When using this encoding I'm getting blury and out of line character throughout my pdf. When using Arial Unicode MS font everything work like expected (but I can't use it due to licensing issues), with any other font I had no success. The result using FreeSans: enter image description here

How I'm adding the font:

ITextRenderer iTextRenderer = new ITextRenderer();
ITextFontResolver iTextFontResolver = iTextRenderer.getFontResolver();
iTextFontResolver.addFont("templates/FreeSans.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

The HTML:

<?xml version="1.0"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <style>
    * {
        font-family: FreeSans;
    }
   </style>
</head>
<body>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
   <p>Test Great White Fox Jumps Over The Hedge?</p>

   ĐĕĞĦķŔŶ
</body>
</html>

How I'm creating the pdf:

iTextRenderer.setDocument(new File(getClass().getClassLoader().getResource("templates/test.html").getFile()));
iTextRenderer.layout();
final FileOutputStream fs = new FileOutputStream("C://temp//temp.pdf");
iTextRenderer.createPDF(fs);

When using a diffrent encoding (for example: WINANSI) the first line of text is rendered correctly but obviously the second line isn't. I really need to be able to create UNICODE (IDENTITY-H) PDFs.

You can download the result pdf using the link below: download pdf from dropbox

Any help is greatly appreciated.

UPDATE: Apparently this had nothing to do with iText or Flying Saucer. Our Maven build builds a single fat jar, the font is also included in this jar. But during the copy from the file system to the jar the font got corrupted.

1 个答案:

答案 0 :(得分:2)

显然这与iText或Flying Saucer无关。我们的Maven构建了一个胖胖的jar,这个字体也包含在这个jar中。但是在从文件系统到jar的复制过程中,字体被破坏了。从过滤中排除字体解决了问题。

 <resources>
     <resource>
         <directory>src/main/resources</directory>
         <filtering>true</filtering>
         <excludes>
             <exclude>templates/font/*.ttf</exclude>
         </excludes>
     </resource>
     <resource>
         <directory>src/main/resources</directory>
         <filtering>false</filtering>
         <includes>
             <include>templates/font/*.ttf</include>
         </includes>
     </resource>
 </resources>