我尝试在从 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);
关于java - 使用 itext 将 html 转换为 pdf 时,自定义字体在 Windows 中有效,但在 Ubuntu 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975409/