【问题标题】:PDF Box Creates ZeroByte PDFPDFBox 创建零字节 PDF
【发布时间】:2018-03-20 13:53:30
【问题描述】:

我正在尝试使用 PDF 框将 unicode 文本文件转换为 PDF。

任务: 我的方法采用 unicode 编码的 TextFile 作为输入并输出 PDF 文件。

问题: 创建的 PDF 的字节数为零。它没有写任何东西。

我正在使用 Apache PDFBox 2.0.6

这是我的代码:

public class TexttoPDF {

    public File texttoPDF(File textFile) throws Exception {

        PDDocument document = new PDDocument();
        PDPage blankPage = new PDPage();
        PDFont font = PDType1Font.TIMES_ROMAN;
        PDPageContentStream contentStream = new PDPageContentStream(document, blankPage);




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


        String str;
        contentStream.beginText();
        contentStream.setFont( font, 12 );
        contentStream.moveTextPositionByAmount( 100, 700 );


        while ((str = in.readLine()) != null) {
            contentStream.drawString(str);


        }


        contentStream.endText();

        document.save( pdffile.getName());
        contentStream.close();
        document.close();
        in.close();



    return pdffile;

    }
}

如何解决这个问题?

【问题讨论】:

    标签: java pdf text unicode pdfbox


    【解决方案1】:

    在保存之前关闭您的内容流,而不是在保存之后。所以改变

        document.save( pdffile.getName());
        contentStream.close();
    

        contentStream.close();
        document.save( pdffile.getName());
    

    (这是described in the FAQ

    在调用new PDPage()后,也将页面添加到您的文档中:

    document.addPage(blankPage);
    

    【讨论】:

    • 它解决了这个问题。然而,只有一行写入 PDF。
    • 是的,这是一个不同的问题。您需要在通话之间拨打contentStream.moveTextPositionByAmount(0,-24);。请注意,您必须自己处理页面更改。请参阅源下载中的 TextToPDF.java。
    猜你喜欢
    • 2012-11-28
    • 2016-06-15
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    相关资源
    最近更新 更多