我尝试在从html转换的pdf文件中显示UTF-8字符(Ş,Ğ等)。我已经阅读了很多问答,并在下面编写了代码。它可以在我的本地计算机(Windows)中运行,但不能在测试服务器(Ubuntu)中运行。测试服务器中未使用该字体,并且缺少某些字符。问题是什么?
我的html文件使用Windows和Ubuntu中不存在的字体。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
* { font-family:'Hickory Jack'; }
</style>
</head>
Java方法:使用htmlText并返回pdf文件的字节。
public static byte[] convertHtmlToPdf(String htmlText) throws Exception{
String fontPath = PdfConverter.class.getResource("/fonts/").getPath();
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(fontPath, null);
FontFactory.setFontImp(fontImp);
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(htmlText.getBytes("UTF-8"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
XMLWorkerHelper xmlWorkerHelper = XMLWorkerHelper.getInstance();
xmlWorkerHelper.parseXHtml(writer, document, is, Charset.forName("UTF-8"),fontImp);
document.close();
byte[] bytes = output.toByteArray();
output.close();
return bytes;
}
问题实际上是路径问题。资源文件的完整路径作为字体路径无效。我这样更改字体提供程序部分,并且可以正常工作。
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register("/fonts/Hickory-Jack.ttf");
fontImp.setUseUnicode(true);
FontFactory.setFontImp(fontImp);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句