PdfBox完整提取pdf文件的指定页

本文介绍了一个使用Apache PDFBox库来实现PDF文档特定页面拆分的方法。通过简单的代码示例,展示了如何加载PDF文档、选择特定页并将其保存为新的PDF文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的第二篇博客,涉及到项目需求,自己研究了一下,功能已经实现,贴出来分享一下,共勉。

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;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值