java - 编辑 iText PDF Java

标签 java pdf itext

我一直在尝试加载位于“/resources/pdf/”的 PDF 文件。我想加载 pdf、填写表单字段并返回一个流。到目前为止,这是有效的,没有错误或异常。 问题在于,打印生成的 PDF 时,文档的某些部分会丢失。使用this pdf ,它只是打印表单字段,而不打印图像或文本。该代码与 primefaces 结合在 tomcat7 中运行:

public StreamedContent modify() {
String pdfFile = "mypdf.pdf";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
    InputStream istream = getClass().getResourceAsStream("/pdf/" + pdfFile);
    PdfReader reader = new PdfReader(istream);

    pdfStamper = new PdfStamper(reader, bos );
    pdfForm = pdfStamper.getAcroFields();

    // fillData();

    pdfStamper.close();
    reader.close();
    istream.close();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    bis.close();
    bos.close();
    return new DefaultStreamedContent( bis, "application/pdf", "report.pdf" ); 

} catch (Exception ex) {
    ex.printStackTrace();
    return null;
}

我以这种方式构建项目:mvn clean install tomcat7:redeploy -DskipTests

知道出了什么问题吗?谢谢。

最佳答案

我最终决定以另一种方式来做。

在项目属性文件中,我添加了一个新属性,其中包含PDF所在的路径,这样我可以通过新的FileInputStream使用File加载pdfReader对象 最终代码

public StreamedContent modify() {
    File file = getPdfFile(); 
    PdfReader reader = new PdfReader(new FileInputStream(file));
    pdfStamper = new PdfStamper(reader, bos );
    // fillData();
    pdfStamper.close();
    bos.close();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    return new DefaultStreamedContent( bis, "application/pdf", "report.pdf" );
}

public File getPdfFile() {
    try {
        Properties prop = new Properties();
        prop.load(getClass().getClassLoader()
               .getResourceAsStream("myfile.properties"));
        String pdfPath = prop.getProperty("pdf.path");
        String pdfName = prop.getProperty("pdf.name");
        File file = new File(pdfPath + pdfName);

        return file;
    } catch (Exception ex) {
        LOGGER.error("ERROR: " + ex.getMessage());
        return null;
    }
}

非常感谢! 问候,

关于java - 编辑 iText PDF Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810205/

相关文章:

java - 想要在Android Studio中单击AlertDialog的确定按钮时更改操作栏图标

pdf - Pandoc:创建表格,Markdown 到 PDF

java - 使用 itext 将多文本添加到现有 pdf

java gc 100% 的 from 和 0% 的 to 空间

java - 打印 Java Swing 时实现带下划线的页眉和页脚

c# - 如何将 asp.net 网页保存为 pdf

pdf - 无法将 pdf 文件转换为我可以搜索的 pdf 文件

java - iText5 : Header content is coming two times while creating PDF

c# - 在IIS上托管的C#中使用USB token 打开X509证书选择

cmd 中的 java.lang.NoClassDefFoundError