pdfbox java.lang.outofmemoryerror_java - Apache PDFBOX-使用split(PDDocument文档)时出现java.lang.OutOfMemory...

PDF Box将拆分操作产生的零件作为PDDocument类型的对象存储为堆中的对象,这导致堆快速填充,即使在循环的每一轮之后调用close()操作,GC仍会无法以与填充相同的方式回收堆大小。

一个选项是将文档拆分操作拆分为多个批次,其中每个批次是一个相对易于管理的块(10至40页)

public void execute() {

File inputFile = new File(path/to/the/file.pdf);

PDDocument document = null;

try {

document = PDDocument.load(inputFile);

int start = 1;

int end = 1;

int batchSize = 50;

int finalBatchSize = document.getNumberOfPages() % batchSize;

int noOfBatches = document.getNumberOfPages() / batchSize;

for (int i = 1; i <= noOfBatches; i++) {

start = end;

end = start + batchSize;

System.out.println("Batch: " + i + " start: " + start + " end: " + end);

split(document, start, end);

}

// handling the remaining

start = end;

end += finalBatchSize;

System.out.println("Final Batch start: " + start + " end: " + end);

split(document, start, end);

} catch (IOException e) {

e.printStackTrace();

} finally {

//close the document

}

}

private void split(PDDocument document, int start, int end) throws IOException {

List fileList = new ArrayList();

Splitter splitter = new Splitter();

splitter.setStartPage(start);

splitter.setEndPage(end);

List splittedDocuments = splitter.split(document);

String outputPath = Config.INSTANCE.getProperty("outputPath");

PDFTextStripper stripper = new PDFTextStripper();

for (int index = 0; index < splittedDocuments.size(); index++) {

String pdfFullPath = document.getDocumentInformation().getTitle() + index + start+ ".pdf";

PDDocument splittedDocument = splittedDocuments.get(index);

splittedDocument.save(pdfFullPath);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值