Java拆分及合并pdf文件
Java拆分及合并pdf文件
- 一、引入spring boot依赖
- 二、工具类
- 三、拆分pdf文件指定开始页到结束页
- 四、Java实现将两个pdf文件合并成一个文件
一、引入spring boot依赖
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
二、工具类
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;import java.io.File;
import java.io.IOException;public class PDFSplitter {public static void splitPDF(String inputPath, String outputPath, int fromPage, int toPage) throws IOException {try (PDDocument document = PDDocument.load(new File(inputPath))) {if (document.isEncrypted()) {throw new IOException("文档已加密,无法进行拆分。");}for (int i = fromPage - 1; i < toPage; i++) {PDPage page = document.getPage(i);PDDocument outputDocument = new PDDocument();outputDocument.addPage(page);String outputFile = outputPath + "page-" + (i + 1) + ".pdf";outputDocument.save(outputFile);outputDocument.close();}}}// 拆分pdf文件,从fromPage到toPage页,public static void splitPDF1(String inputPath, String outputPath, int fromPage, int toPage) throws IOException {try (PDDocument document = PDDocument.load(new File(inputPath))) {if (document.isEncrypted()) {throw new IOException("文档已加密,无法进行拆分。");}PDDocument outputDocument = new PDDocument();for (int i = fromPage - 1; i < toPage; i++) {PDPage page = document.getPage(i);outputDocument.addPage(page);}String outputFile = outputPath + "page" + fromPage + "-" + toPage + ".pdf";outputDocument.save(outputFile);outputDocument.close();}}// 将两个pdf文件,合并成一个pdf文件public static void mergePDF(String file1, String file2, String outputPath) {// 创建 PDFMergerUtility 实例PDFMergerUtility pdfMerger = new PDFMergerUtility();// 设置合并后的PDF文件的输出路径pdfMerger.setDestinationFileName(outputPath + "merge.pdf");// 添加要合并的PDF文件try {pdfMerger.addSource(new File(file1));pdfMerger.addSource(new File(file2));// 合并文档pdfMerger.mergeDocuments(null);} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {try {splitPDF1("D:\\2.要你命2000合集.pdf", "D:\\新建文件夹\\", 1, 99); // 拆分从第1页到第3页的PDF// mergePDF("D:\\新建文件夹\\page1-300.pdf", "D:\\新建文件夹\\page99-300.pdf", "D:\\新建文件夹\\");} catch (IOException e) {e.printStackTrace();}}
}
三、拆分pdf文件指定开始页到结束页
将指定文件只想拆分出1-300页,如图该文件共有722页

但只想要前300页,则调用工具类中的splitPDF1方法,则拆分得到了page1-300.pdf文件,文件内容无误

public static void main(String[] args) {try {splitPDF1("D:\\2.要你命2000合集.pdf", "D:\\新建文件夹\\", 1, 99); // 拆分从第1页到第3页的PDF} catch (IOException e) {e.printStackTrace();}}
四、Java实现将两个pdf文件合并成一个文件
如图目录中有两个文件,目前想将这两个文件合并成一个文件,调用工具类里的mergePDF方法,会生成一个merge.pdf文件


public static void main(String[] args) {mergePDF("D:\\新建文件夹\\page1-300.pdf", "D:\\新建文件夹\\page99-300.pdf", "D:\\新建文件夹\\");}
