JAVA将一个pdf按页码拆分成多个pdf

 

 

引入maven

   <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcmail-jdk15on</artifactId>
            <version>1.47</version>
        </dependency>

 

 

public static void main(String[] args) throws Exception {
        // 根据页码拆分pdf,有多少页就拆成多少张pdf
        File file = new File("pdf文件绝对路径");
        PdfReader pdfReader = new PdfReader(new FileInputStream(file));
        int pages = pdfReader.getNumberOfPages();
        // 设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        for (int i = 1; i <= pages; i++) {
            PdfReader reader = new PdfReader("pdf文件绝对路径");
            Document doc = new Document();
            // 每个pdf命名规则:时间戳(2019109143408)+"-"+顺序编号(i)
            String pdfName =  "D:/test/" + df.format(new Date()) + "-" + i + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfName));
            doc.open();
            PdfContentByte cb = writer.getDirectContent();
            doc.newPage();
            cb.addTemplate(writer.getImportedPage(reader, i), 0, 0);
            doc.close();
            writer.close();
            reader.close();
        }
    }

 

posted @ 2021-03-18 22:42  yvioo  阅读(555)  评论(0编辑  收藏  举报