1 配置pom文件
我用的是5.4.3的版本
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
2 按页(逐页、单页)拆分PDF代码
/**
* @author Reverse_XML
* 把PDF 按页(逐页、单页)拆分(一页一页拆分,一页为一个新PDF文件)
* @param path 源PDF路径
* @param fileName 源PDF文件名
* @param outputPath 拆分后输出的PDF路径
*/
public static void splitPDFOneByOne(String path, String fileName, String outputPath) {
String sep = java.io.File.separator;
PdfReader reader = null;
int numberOfPages = 0;
try {
reader = new PdfReader(path + sep + fileName);
numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
Document document = null;
PdfCopy copy = null;
try {
document = new Document(reader.getPageSize(1));
String savePath = outPath + sep +
fileName.substring(0, fileName.lastIndexOf(".")) + "_" + i + ".pdf";
copy = new PdfCopy(document, new FileOutputStream(savePath));
document.open();
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
} finally {
if (document != null)
document.close();
if (copy != null)
copy.close();
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (DocumentException e) {
log.error(e.getMessage(), e);
} finally {
if (reader != null)
reader.close();
}
}
3 调用示例
将指定的PDF逐页拆分(一页一页拆分,一页为一个新的PDF)
public static void main(String[] args) {
try {
PDFUtils.splitPDFOneByOne("D:\\inputPath", "test.pdf", "D:\\outputPath");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}