itextpdf截取pdf文件为新文件

首先引用itextpdf依赖:

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

 测试类:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

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

public class PDFTest {

    public static void main(String[] args) {
        splitPDFFile("e:/glossary_old.pdf", "e:/glossary01.pdf","e:/glossary_new.pdf", 2, -1);
    }

    /**
     * 截取pdfFile的第from页至第end页,组成一个新的文件名
     * @param respdfFile  需要分割的PDF1
     * @param respdfFile2  需要分割的PDF2
     * @param savepath  新PDF
     * @param from  起始页
     * @param end  结束页
     */
    public static void splitPDFFile(String respdfFile, String respdfFile2, String savepath, int from, int end) {
        Document document = null;
        PdfCopy copy = null;
        try {
            PdfReader reader1 = new PdfReader(respdfFile2);
            PdfReader reader = new PdfReader(respdfFile);
            int n = reader.getNumberOfPages();
            if(end <= 0){
                end = n;
            }
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            document.newPage();
            //写入respdfFile2的第一页作为首页
            PdfImportedPage page1 = copy.getImportedPage(reader1, 1);
            copy.addPage(page1);

            //写入respdfFile的from到end页
            for(int j = from; j <= end; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            document.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch(DocumentException e) {
            e.printStackTrace();
        }
    }
}

生成的文件内容是包含glossary01.pdf的首页和 glossary_old.pdf第2页到尾页的名为glossary_new.pdf的文件。

猜你喜欢

转载自blog.csdn.net/aleefang/article/details/114262654