简体   繁体   中英

How do I use custom fonts for AcroForm fields in a PDF generated from XHTML with Flying Saucer and OpenPDF?

I seem to have a problem that I'm unable to solve on my own. I'm using flyingsaucer-9.1.20 with openpdf-1.3.22 to generate PDFs from an XHTML source.

My customer's CI demands Verdana as font for all their documents. So I embedded the font and created the PDF as shown in the following example:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(xhtmlDoc);
renderer.getFontResolver().addFont(fontDir + "verdana.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);  
renderer.layout();
renderer.createPDF(outputStream);

And here is a sample XHTML source:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">     
  body {
    font-size: 7.5pt;
    font-family: Verdana;
  }
  input {
    font-size: 7.5pt;
    width: 500px;
    height: 15px;
    font-family: Verdana;
  }  
</style>
</head>
<body>
  TestField: <input type="text" value="Test"></input>
  <p>This is an example Text</p>
</body>
</html>

This is how the generated PDF file looks like in Adobe Acrobat Reader DC:

pdf1

So far so good, it uses my embedded font, but as soon as I click the input field, font changes and after editing, it stays that way:

pdf2

When I open the PDF in Chrome and click the input field, it looks like this:

pdf3

Mostly blanks and sometimes some random letters as seen in this example from my actual project:

例子

It looks like there is some kind of encoding issue and Adobe Acrobat Reader falls back to its default font. When I use one of the standard fonts from OpenPDF it works just fine. I've been struggling with this problem for some days now and I just can't wrap my head around it.

Am I missing something?

I managed to resolve this issue by changing

renderer.getFontResolver().addFont(fontDir + "verdana.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

to

renderer.getFontResolver().addFont(fontDir + "verdana.ttf", BaseFont.CP1257, BaseFont.EMBEDDED);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM