我的第二篇博客,涉及到项目需求,自己研究了一下,功能已经实现,贴出来分享一下,共勉。
idea maven项目
pom 依赖 :
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.8.10</version> </dependency>
方法实现:
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; import org.apache.pdfbox.util.Splitter;public static String splitPdf(int pageNum, String filePath, String fileName, String outPath) { File indexFile = new File(filePath);// 这是对应文件名 PDDocument document = null; try { document = PDDocument.load(indexFile); Splitter splitter = new Splitter(); splitter.setStartPage(pageNum); splitter.setEndPage(pageNum); java.util.List<PDDocument> pages = splitter.split(document); ListIterator<PDDocument> iterator = pages.listIterator(); while (iterator.hasNext()) { File file = new File(outPath); if (!file.exists()) { file.mkdirs(); } PDDocument pd = iterator.next(); File newFile = new File(outPath + fileName); if (newFile.exists()) { newFile.delete(); } pd.save(outPath + fileName); pd.close(); if (newFile.exists()) { return newFile.getPath(); } } document.close(); } catch (IOException e) { e.printStackTrace(); } catch (COSVisitorException e) { e.printStackTrace(); } return null; }