这是我花在调查中的第二天没有结果。至少现在,我能够提出一些非常具体的问题。使用ITextRenderer从HTML生成非拉丁字符的PDF不起作用
我想写使用iText更具体使用ITextRenderer从Flying Saucer包含在PDF文件中的一些非拉丁字符有效的HTML代码。
我的小例子/代码通过初始化字符串变量DOC该值:
String doc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">"
+ "<body>Some greek characters: Καλημέρα Some greek characters"
+ "</body></html>";
这里是我在调试时使用的代码。我这个字符串保存为HTML文件,然后我打开它通过浏览器只是为了仔细检查HTML内容有效,我仍然可以读希腊字符:
//write for debugging purposes in an html file
File newTextFile = new File("C:/work/test.html");
FileWriter fw = new FileWriter(newTextFile);
fw.write(doc);
fw.close();
下一步是尝试写在这个值PDF文件。这是我的代码:
ITextRenderer renderer = new ITextRenderer();
//add some fonts - if paths are not right, an exception will be thrown
renderer.getFontResolver().addFont("c:/work/fonts/TIMES.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("c:/work/fonts/TIMESBD.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("c:/work/fonts/TIMESBI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("c:/work/fonts/TIMESI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
documentBuilderFactory.setValidating(false);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.setEntityResolver(FSEntityResolver.instance());
org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(
doc.toString().getBytes("UTF-8")));
renderer.setDocument(document, null);
renderer.layout();
renderer.createPDF(os);
我的代码的最终结果是:
在HTML文件我得到:一些希腊字符:Καλημέρα一些希腊字符(预期)
在PDF文件我得到:一些希腊字符:一些希腊字符(意想不到 - 希腊字符被忽略!)
依赖关系:
Java版本 “1.6.0_27”
iText的 - 2.0.8.jar
de.huxhorn.lilith.3rdparty。 flyingsaucer.core-renderer-8Pre2.jar
我也已经尝试过很多莫重新字体,但我想我的问题与使用错误的字体无关。任何帮助都比欢迎。
感谢名单
刚刚试过,没有好消息:(我得到的结果相同 @Ravinder我想你错过了在你的例子中:P – alexandros 2012-04-20 20:09:11
@alexandros:请检查我的答案的更新。 – 2012-04-20 20:30:51
我在我的测试中添加了这个:System.out.println(“file.encoding =”+ System.getProperty(“file.encoding”));打印结果如下:file.encoding = UTF-8。这应该足以确保我有正确的编码? – alexandros 2012-04-20 20:51:11