java - IText5 - 使用相同内容和 SmartPdfCopy 创建 10000 页 PDF 时占用大量内存

标签 java pdf itext

我正在尝试使用单个模板 PDF 和 AcroForm 生成 10000 页 PDF,在此过程中我将填充值。

我的问题是,我遇到了 OOME,并且应用程序本身消耗了 4GB。如何降低内存消耗?

我如何创建我的内容:

public PDFBuilderItext5(InputStream templateSource) throws DocumentException, IOException {
        templateBytes = readTemplateToBytes(templateSource);
//      output = new ByteArrayOutputStream();
        output = new BufferedOutputStream(new FileOutputStream("z:\\itext\\buff.pdf"));
        document = new Document();
        copy = new PdfSmartCopy(document, output);
        document.open();
    }

这是在循环中完成的:

ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(templateBytes);
        PdfStamper stamper = new PdfStamper(reader, tempOut);
        try {
            AcroFields fields = stamper.getAcroFields();
//          fields.setGenerateAppearances(true);
            Set<String> fieldNames = fields.getFields().keySet();
            FieldValueBuilder fb = new FieldValueBuilder(t);
            for (String fn : fieldNames) {
                String label = fields.getField(fn);
                String value = fb.valueFor(label);
                fields.setField(fn, value,value);
            }
            stamper.setFormFlattening(true);

        } finally {
            stamper.close();
            reader.close();
        }
        append(tempOut.toByteArray());

private synchronized void append(byte[] pdfContent) throws DocumentException, IOException{
    PdfReader reader = new PdfReader(pdfContent);
    copy.addDocument(reader);
    reader.close();
    notFlushedPagesCount++;
    if(notFlushedPagesCount>=FLUSH_INTERVAL){
        copy.flush();
        System.out.println("Flushed copy");
        notFlushedPagesCount=0;
    }
}

我感觉我没有在某个地方释放一些资源,因为:

enter image description here

最佳答案

你永远不会“释放”读者。

例如:

private synchronized void append(byte[] pdfContent)
    throws DocumentException, IOException{
    PdfReader reader = new PdfReader(pdfContent);
    copy.addDocument(reader);
    copy.freeReader(reader);
    reader.close();
}

关于java - IText5 - 使用相同内容和 SmartPdfCopy 创建 10000 页 PDF 时占用大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43515342/

相关文章:

Java:如果我有一个正在运行的程序实例,我如何检测到它,然后关闭旧的

java - 在某些特定情况下更喜欢编译时常量而不是枚举

bash - 从一系列 PDF 中删除第一页

c# - 拒绝访问!?我无法从 C 驱动器上的安装文件夹中打开文件

java - 有没有一种方法可以在java中执行一段代码而不将其放入静态main方法中

java - Jenkins 和 NodeJS 插件 - 权限被拒绝错误 = 13

java - 我怎样才能写出文本文档中的所有页面

c# - 在itextsharp中为pdfpcell添加圆形颜色边框

javascript - 如何从浏览器打印 PDF

c# - 在 C# 中读取 PDF