PdfBox完整提取pdf檔案的指定頁
阿新 • • 發佈:2019-02-13
我的第二篇部落格,涉及到專案需求,自己研究了一下,功能已經實現,貼出來分享一下,共勉。
idea maven專案
pom 依賴 :
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.8.10</version> </dependency>
方法實現:
importorg.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; }