我想從 PDF 檔案中獲取一部分頁面。基本上,我給函式一個檔案,將其拆分為頁面,然后創建一個新檔案,其中僅包含起始頁面和結束頁面之間的頁面。當用戶輸入頁碼時,我需要從 0 開始的串列更正。這是我擁有的代碼。
public static String SplitPdf(File source, Integer startPage, Integer endPage) throws Exception {
String sourceFileName = source.getAbsolutePath().replace("\\", "/");
File file = new File(sourceFileName);
PDDocument document = PDDocument.load(file);
Splitter splitter = new Splitter();
List<PDDocument> pages = splitter.split(document);
Integer correctedStartPage = startPage < 1 ? 1 : startPage - 1;
Integer correctedEndPage = endPage < 1 ? 1 : endPage - 1;
if (pages.size() <= correctedStartPage) throw new Exception("Start page: " startPage " No of pages: " pages.size());
if (pages.size() <= correctedEndPage) throw new Exception("End page: " endPage " No of pages: " pages.size());
if (startPage > endPage)
throw new Exception("Start page before end page. Start page: " startPage " End page: " endPage);
PDDocument newDoc = new PDDocument();
String filePath = file.getParent() "\\" FilenameUtils.getBaseName(file.getName()) "-fittingPart"
"." FilenameUtils.getExtension(file.getName());
for (int i = correctedStartPage; i <= correctedEndPage; i ) {
PDDocument currentPage = pages.get(i);
PDPage page = currentPage.getPage(0);
newDoc.addPage(page);
currentPage.close();
}
newDoc.save(filePath);
newDoc.close();
return filePath;
}
我得到的錯誤是:
COSStream 已關閉,無法讀取。也許其封閉的 PDDocument 已關閉?
我確實檢查了檔案是否存在
據我所知,我并沒有過早關閉 PDDocument ......有什么想法嗎?
PS:我需要使用 apache PDFBox 而不是其他庫??
uj5u.com熱心網友回復:
您需要關閉所有 PDDocument 物件、源物件和您生成的物件,splitter而不僅僅是最終物件。您還應該使用拆分器方法讓您的生活更輕松,setStartPage()而setEndPage()不是創建所有這些中間檔案然后獲取第一個檔案。確保僅在所有物件都保存后才關閉物件(由于可能共享資源)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410363.html
標籤:
上一篇:從PDF中提取準確的表格資料
