java - jPod 是否通过数据流合并 PDF?

标签 java pdf streaming

我正在使用 jPod 来合并我的 PDF 文档。我合并了每 20 页 400 个 PDF,生成了 190 MB 的文件,而单个 pdf 的大小为 38 KB。我在 IDE 中检查了堆状态。我没有收到任何内存不足错误。我在 Apache Tomcat 中运行了同样的程序,有近 30 个客户端。我的 Tomcat 停止服务请求。是不是因为,jPod 不使用 Streaming 还是由于其他一些原因??

private void run() throws Throwable {
String sOutFileFullPathAndName = "/Users/test/Downloads/" + UUID.randomUUID().toString().replace("-", "");
PDDocument dstDocument = PDDocument.createNew();

for (int i = 0;i < 400; i++) {
    //System.out.println(Runtime.getRuntime().freeMemory());
    PDDocument srcDocument = PDDocument.createFromLocator(new FileLocator("/Users/test/Downloads/2.pdf") );   
    mergeDocuments(dstDocument, srcDocument);
}
FileLocator destinationLocator = new FileLocator(sOutFileFullPathAndName);
dstDocument.save(destinationLocator, null);
dstDocument.close();
}

private void mergeDocuments(PDDocument dstDocument, PDDocument srcDocument) {
PDPageTree pageTree = srcDocument.getPageTree();
int pageCount = pageTree.getCount();
for (int index = 0; index < pageCount; index++) {
    PDPage srcPage = pageTree.getPageAt( index );
    appendPage(dstDocument, srcPage);

    srcPage = null;
}
}

private void appendPage(PDDocument document, PDPage page) {
PDResources srcResources = page.getResources();
CSContent cSContent = page.getContentStream();
PDPage newPage = (PDPage) PDPage.META.createNew();

// copy resources from source page to the newly created page

PDResources newResources = (PDResources) PDResources.META
    .createFromCos(srcResources.cosGetObject().copyDeep());
newPage.setResources(newResources);
newPage.setContentStream(cSContent);

// add that new page to the destination document

document.addPageNode(newPage);
}

最佳答案

PDF 不仅仅是页面数据的“流”。它是一个复杂的数据结构,包含相互引用的对象。在这个具体案例中,页面树/节点、内容流、资源……

jPod 仅使用弱引用将持久对象保留在内存中 - 它们始终可以从随机访问数据中刷新。如果开始更新对象结构,对象将被“锁定”在内存中,因为更改不是持久的并且无法再刷新。

进行大量更改而不定期保存结果会将完整的结构保留在内存中 - 我认为这就是您的问题。时不时地保存应该会减少内存占用。

此外,该算法将创建一个较差的页面树,其中包含数千个页面的线性数组。您应该尝试创建平衡的树结构。优化的另一点是资源处理。合并字体或图像等资源可能会显着减小目标大小。

关于java - jPod 是否通过数据流合并 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51520326/

相关文章:

python - 在 Python 中创建和写入 pdf 文件

java - Spring MVC + Oracle LOB + 流式处理

html - 如何使用 ffmpeg 通过 http 流式传输

java - 设置公共(public)类以供其他项目访问

java - 无法正确排序我的数组列表

java - 使用 Hibernate 识别另一个实体中的实体的问题

java - 如何只替换数字后面的双引号?

swift - 无法在 swift 中共享 pdf(仅限 WhatsApp)

twitter - 启动 Spark 流上下文时出错

pdf - JPG 到 PDF 转换,如何适应整页