Edit iText PDF Java



我一直在尝试加载位于"/resources/pdf/"的PDF文件。我想加载 pdf,填写表单字段并返回流。到目前为止,这是有效的,没有错误或异常。问题是,当打印生成的PDF时,文档的部分内容丢失了。使用此pdf,它只是打印表单字段,而不是图像或文本。该代码在 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 加载带有文件的 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;
    }
}

谢谢!问候

更新:我刚刚遇到了同样的问题!经过深入研究,我发现 maven 破坏了我的 PDF 文件的编码。我应该更仔细地阅读 MKL 的评论;-(

我将资源插件添加到我的 maven 项目中:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <nonFilteredFileExtensions>
        <!-- Please note that images like jpg, jpeg, gif, bmp and png are (already) implicitly excluded -->
            <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

旧帖子:

您的帖子缺少重要信息:

  1. 您如何打印报告.pdf?从网络浏览器或Adobe Reader?请发布报告.pdf以便我们进行分析。
  2. 我的理解是,您发布的代码工作正常(没有错误,没有例外(。仅在打印时出现问题?

一枪可能出了什么问题:

您没有为流设置编码(例如 UTF-8(:

return new DefaultStreamedContent( bis, "application/pdf", "report.pdf", "YourEncoding");

顺便说一下,原始PDF也有错误(例如,印前检查报告服务器错误。

最新更新