Java分割PDF文件(itextpdf)

使用itextpdf,对PDF文件进行分割

maven依赖

<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itextpdfartifactId>
    <version>5.5.13version>
dependency>
实现工具类代码
package com.example.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * PDF处理工具类
 *
 * @author azhuzhu 2020/8/11 14:53
 */
@Slf4j
public class PdfUtil {

    /**
     * 将PDF文件切分成多个PDF
     *
     * @param filename  文件名
     * @param splitSize 拆分单个文件页数
     */
    public static void splitPdf(String filename, int splitSize) throws Exception {
        PdfReader reader;
        try {
            reader = new PdfReader(filename);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new Exception("读取PDF文件失败");
        }
        int numberOfPages = reader.getNumberOfPages();
        int newFileCount = 0;
        // PageNumber是从1开始计数的
        int pageNumber = 1;
        while (pageNumber <= numberOfPages) {
            Document doc = new Document();
            String splitFileName = filename.substring(0, filename.length() - 4) + "(" + newFileCount + ").pdf";
            PdfCopy pdfCopy;
            try {
                pdfCopy = new PdfCopy(doc, new FileOutputStream(splitFileName));
            } catch (FileNotFoundException | DocumentException e) {
                log.error(e.getMessage(), e);
                throw new Exception("切割文件副本创建失败");
            }
            doc.open();
            // 将pdf按页复制到新建的PDF中
            for (int i = 1; pageNumber <= numberOfPages && i <= splitSize; ++i, pageNumber++) {
                doc.newPage();
                PdfImportedPage page = pdfCopy.getImportedPage(reader, pageNumber);
                pdfCopy.addPage(page);
            }
            doc.close();
            newFileCount++;
            pdfCopy.close();
        }
    }

}

测试类
package com.example.demo;

import com.example.util.PdfUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Test
    void contextLoads() throws Exception {
        PdfUtil.splitPdf("D:/组合 2.pdf", 1);
    }

}
执行结果

Java分割PDF文件(itextpdf)_第1张图片

你可能感兴趣的:(代码笔记)