itextpdf拆分pdf

该代码示例展示了如何在Java中引入PDFbox和iTextPDF库,通过URL下载PDF文件,读取页面内容,然后将每个页面保存为新的PDF文件。过程中涉及PDFReader、PdfCopy和Document等类的使用,以及文件路径处理和异常处理。
摘要由CSDN通过智能技术生成

引入jar包,pdfbox和itextpdf,pom文件如下

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.9</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>         

 废话不说直接上干货

        List<String> filePath = new ArrayList();
        String sep = java.io.File.separator;
        PdfReader reader = null;
        int numberOfPages;
        String saveBasePath = FileUtils.getFolderName(UUID.randomUUID().toString().replaceAll("-", ""));
        try {
            URL url = new URL(ossFileDTO.getDownloadUrl());
            reader = new PdfReader(url);
            numberOfPages = reader.getNumberOfPages();
            for (int i = 1; i <= numberOfPages; i++) {
                Document document = null;
                PdfCopy copy = null;
                try {
                    document = new Document(reader.getPageSize(i));
                    
                    String fileName_half ;
                    String text_i = PdfTextExtractor.getTextFromPage(reader, i);
                    
                    fileName_half = fileName_half.replaceAll("[:*|,*|:*|,*| *| *| *|\\s*]*", "");
                    String savePath = saveBasePath + sep +
                            ossFileDTO.getFilename().substring(0, ossFileDTO.getFilename().lastIndexOf(".")) + "_"+ i + fileName_half + ".pdf";

                    File file = new File(saveBasePath, savePath);
                    File fileParent = file.getParentFile();
                    if (!fileParent.exists()) {
                        fileParent.mkdirs();
                    }
                    copy = new PdfCopy(document, new FileOutputStream(savePath));
                    document.open();
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    copy.addPage(page);
                    filePath.add(savePath);
                } catch (Exception e) {
                    Log.error("上传oss失败!",e);
                } finally {
                    if (document != null)
                        document.close();
                    if (copy != null)
                        copy.close();
                }
            }
        } catch (Exception e){
            log.error("转换失败!",e);
        } finally {
            if (reader != null){
                reader.close();
            }
        }

总结:获取到filePath 后,根据自己的需求,进行灵活使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值