Search code examples
itextflying-saucer

HTML to PDF using custom font (Identity-H)


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.


Solution

  • 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. Excluding the font from filtering solved the issues.

     <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>