原文地址
需要用到的jar包 https://pan.baidu.com/s/1hQolDOjN2Xi9b_brwB2TcQ 提取码idk2
/**
* 拆分PDF代码, 假如我只想拆分第一页, 那么from和to就是1, 1。
* 如果需要拆分从第一页到第五页, 那么from和to就是1, 5。
* @param pdfFile 需要拆分的源文件
* @param newFile 生成新PDF的路径
* @param from 从哪一页开始
* @param end 从哪一页结束
*/
public static void partitionPdfFile(String pdfFile, String newFile, int from, int end) {
Document document = null;
PdfCopy copy = null;
try {
PdfReader reader = new PdfReader(pdfFile);
int n = reader.getNumberOfPages();
if (end == 0){
end = n;
}
ArrayList<String> savepaths = new ArrayList<String>();
String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\")+1);
String savepath = staticpath+ newFile;
savepaths.add(savepath);
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
document.open();
for(int j=from; j<=end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch(DocumentException e) {
e.printStackTrace();
}
}