将很多页的PDF文件分割为小的PDF文件,解决打开慢和占用内存多的问题。
背景:打开很多页的PDF文件很慢,因为PDF阅读器需要耗费很多内存空间和CPU资源去渲染PDF页面。
解决方案:使用pdfbox类库分割PDF文件
引入Maven依赖包
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.28</version>
</dependency>
编写Java代码
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
/**
* 分割PDF文件
*/
public class PdfCut {
/**
* 每小份PDF文件的最大页数
*/
private static final int MAX_PAGE_SIZE = 80;
/**
* 待分割的PDF文件
*/
private static final String SOURCE_FILE_PATH = "D:\\Mysql从入门到跑路.pdf";
/**
* 分割生成的小份PDF文件的保存位置
*/
private static final String TARGET_DIR = "F:\\学习资料";
public static void main(String[] args) throws Exception {
File sourceFile = new File(SOURCE_FILE_PATH);
//读取PDF文件
PDDocument pdDocument = PDDocument.load(sourceFile);
int numberOfPages = pdDocument.getNumberOfPages();
String sourceFileName = sourceFile.getName();
int index = sourceFileName.lastIndexOf(".");
//截取文件名和扩展名
String a = sourceFileName.substring(0, index);
String b = sourceFileName.substring(index);
System.out.println(numberOfPages);
if (numberOfPages <= 0) {
return;
}
//页码基数
int top = 0;
//文件编号
int order = 1;
//循环分割
do {
PDDocument save = new PDDocument();
//从待分割文件中获取指定页面
for (int i = 0; (i < MAX_PAGE_SIZE && (top + i) < numberOfPages); i++) {
save.addPage(pdDocument.getPage(top + i));
}
//保存分割形成的文件
save.save(new File(TARGET_DIR + File.separator + a + "-" + order + b));
save.close();
//编号加1
order++;
//基数加上最大页数
top += MAX_PAGE_SIZE;
} while (top < numberOfPages);
}
}