Java - PDFBox 1.8.9 unicode textfile到pdf

时间:2015-07-13 13:23:39

标签: java pdf unicode pdfbox

我在SO上忽略了与此问题相关的所有问题,但无法找到并回答。

我有一个textFile,其中包含unicode字符,如“ā”,“š”,“ī”等。 问题是,当我将textFile写入PDF时,pdf文件无法正确显示。

如何设置我的代码,所以我可以在我的PDF上写这些字符? 也许更好的问题是:这甚至可能吗?因为我一直在寻找这个几个小时,但找不到解决方案。

由于此应用程序将是商业用途,我无法使用iText!

我的代码:

TextToPDF pdf = new TextToPDF();
String fileName = "test.txt";
File pdfFile = new File("test.pdf");

BufferedReader reader = new BufferedReader(new FileReader(fileName));

PDSimpleFont courier = PDType1Font.COURIER;
PDSimpleFont testFont = PDTrueTypeFont.loadTTF( document, new File("times.ttf" ));

pdf.setFont(testFont);
pdf.setFontSize(8);

pdf.createPDFFromText(document, reader);

document.save(pdfFile);
document.close();

如果有人这样做了,请分享你是如何做到的。我认为它应该与font.setFontEncoding();相关但是由于PDFBox文档缺少相当多的信息,我没有想出来,我应该做什么或如何做。

顺便说一下,这里是我读过的SO问题列表,所以请不要将我重新定向给他们......

1)Java PDFBOX text encoding

2)Using Java PDFBox library to write Russian PDF

3)Using PDFBox to write UTF-8 encoded strings to a PDF

我阅读了更多主题,但这些主题仍在我的标签中打开。

编辑:刚发现这个 - > Using PDFBox to write unicode strings to a PDF

似乎不可能,需要更新到2.0.0版本并尝试一下。

编辑#2:在新版本的PDFBox 2.0.0(至少现在)已删除了TextToPDF()类,它允许我传入textFile。所以现在意味着,我手动阅读文本,然后将其写入PDF,或者需要找到其他解决方案。

3 个答案:

答案 0 :(得分:0)

你的问题在这里:

BufferedReader reader = new BufferedReader(new FileReader(fileName));

如此处所述:http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html FileReader将以系统默认编码读取文件。 将其更改为:

BufferedReader in = new BufferedReader(
           new InputStreamReader(
                      new FileInputStream(fileDir), "UTF8"));

如果是UTF-8,这将以UTF-8读取您的文件。你所描述的特殊字符存在于像iso latin 1等字符编码中。

当您知道输入的编码时,请确保以此编码方式读取它。然后PDFBox也可以用他想要的编码来编写它们。

答案 1 :(得分:0)

刚发现这个 - > Using PDFBox to write unicode strings to a PDF

似乎不可能,需要更新到2.0.0并尝试一下。

编辑#2:新版PDFBox 2.0.0(至少现在) 已删除类TextToPDF()(在评论中,已经说过它现在可用了) 这让我传入textFile。所以现在意味着,我手动阅读文本,然后将其写入PDF,或者需要找到其他解决方案

答案 2 :(得分:-1)

you can create a pdf by simply creating a file with .pdf extension 
You are going to create pdf file like this way  "**File pdfFile = new File("test.pdf")**"  but itsn't correct way . please go through below code how to crate pdf file .

    public static void main(String arg[]){
       this.create("test.pdf");`enter code here`enter code here`
    }
    public void create(String file) throws IOException {*enter code here*
      PDDocument document=null;
      try {
        document=new PDDocument();
        PDPage blankPage=new PDPage();
        document.addPage(blankPage);
        document.save(file);
      }
      finally {
        if (document != null) {
          document.close();
        }
      }
    }

and also go through below link **http://www.javased.com/api=org.apache.pdfbox.pdmodel.PDDocument**