Java使用iText PDF按页(逐页、单页)拆分PDF

1 配置pom文件

我用的是5.4.3的版本

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.4.3</version>
</dependency>
2 按页(逐页、单页)拆分PDF代码
/**
 * @author Reverse_XML
 * 把PDF 按页(逐页、单页)拆分(一页一页拆分,一页为一个新PDF文件)
 * @param path 源PDF路径
 * @param fileName 源PDF文件名
 * @param outputPath 拆分后输出的PDF路径
 */
public static void splitPDFOneByOne(String path, String fileName, String outputPath) {
    String sep = java.io.File.separator;
    PdfReader reader = null;
    int numberOfPages = 0;
    try {
        reader = new PdfReader(path + sep + fileName);
        numberOfPages = reader.getNumberOfPages();
        for (int i = 1; i <= numberOfPages; i++) {
            Document document = null;
            PdfCopy copy = null;
            try {
                document = new Document(reader.getPageSize(1));
                String savePath = outPath + sep +
                        fileName.substring(0, fileName.lastIndexOf(".")) + "_" + i + ".pdf";
                copy = new PdfCopy(document, new FileOutputStream(savePath));
                document.open();
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, i);
                copy.addPage(page);
            } finally {
                if (document != null)
                    document.close();
                if (copy != null)
                    copy.close();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (DocumentException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (reader != null)
            reader.close();
    }
}
3 调用示例

将指定的PDF逐页拆分(一页一页拆分,一页为一个新的PDF)

public static void main(String[] args) {
    try {
        PDFUtils.splitPDFOneByOne("D:\\inputPath", "test.pdf", "D:\\outputPath");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
4 官网

https://itextpdf.com

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值