Java:使用 PDFBox 将国家字符写入 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13274578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Write national characters to PDF using PDFBox
提问by Firzen
Possible Duplicate:
Using PDFBox to write UTF-8 encoded strings to a PDF
I need to create PDF with Czech national characters, and I'm trying to do it with PDFBox library. I have copied following code from some tutorials:
我需要使用捷克国家字符创建 PDF,我正在尝试使用 PDFBox 库来实现。我从一些教程中复制了以下代码:
public void doIt(String file, String message) throws IOException, COSVisitorException
{
PDDocument doc = null;
try
{
doc = new PDDocument();
PDSimpleFont font = PDType1Font.TIMES_ROMAN;
TextToPDF textToPdf = new TextToPDF();
textToPdf.setFont(font);
textToPdf.setFontSize(12);
doc = textToPdf.createPDFFromText(new StringReader(message));
doc.save(file);
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
Now, I'am calling function doIt:
现在,我正在调用函数 doIt:
app.doIt("test.pdf", "Skákal pes p?es oves, p?es zelenou louku.");
This completely works, but in output PDF I get: "t?Skákal pes pYes oves, pYes zelenou louku."
这完全有效,但在输出 PDF 中我得到:“t?Skákal pes pYes oves,pYes zelenou louku。”
I tried to find how to set UTF-8 encoding in PDFBox, but IMHO there is just no solution for this on the internet.
我试图找到如何在 PDFBox 中设置 UTF-8 编码,但恕我直言,互联网上没有解决方案。
Do you have any ideas, how to get right text in output PDF?
您有什么想法,如何在输出 PDF 中获得正确的文本?
Thank you.
谢谢你。
采纳答案by Yogendra Singh
I think its PDType1Font.TIMES_ROMAN
font which is not supporting your Czech national characters. If you can manage to get the .ttf
files for the Czech national characters
, then use below to get PDFont
as below and use the same:
我认为它的PDType1Font.TIMES_ROMAN
字体不支持您的捷克民族字符。如果你能设法得到.ttf
的文件Czech national characters
,然后输入如下得到PDFont
如下,并使用相同:
PDFont font = PDTrueTypeFont.loadTTF( doc, new File( "CheckRepFont.ttf" ) );
Here CheckRepFont.ttf
is your font file name as an example. Update it with actual one.
这CheckRepFont.ttf
是您的字体文件名作为示例。用实际的更新它。
EDIT:
编辑:
PDStream pdStream = new PDStream(doc);
PDSimpleFont font = PDType1Font.TIMES_ROMAN;
font.setToUnicode(pdStream);