有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java PDF Box创建零字节PDF

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

任务: 我的方法将unicode编码的文本文件作为输入,并输出PDF文件

问题: 创建的PDF没有字节。它什么也没写

我在用 ApachePDFBOx2.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;

    }
}

如何解决这个问题


共 (1) 个答案

  1. # 1 楼答案

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

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

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

    (这里是described in the FAQ

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

    document.addPage(blankPage);