ITextPDF7 的一些功能的使用

ITextPDF7 的一些功能的使用

1、创建Maven工程,导入依赖


	<dependency>
	    <groupId>com.itextpdfgroupId>
	    <artifactId>itext7-coreartifactId>
	    <version>7.0.3version>
	    <type>pomtype>
	dependency>

部分实例:

2、分割PDF文件

//多页分割单页实现
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PageRange;
import com.itextpdf.kernel.utils.PdfSplitter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
//每页分页
public class PDFSplitter {
	//需要被分割的文件
    private static final String ORIG = "E:/pdf/signed_out.pdf";
    private static final String OUTPUT_FOLDER = "E:/pdf/myfiles/";


    public static void main(String args[]) throws IOException {
        final int maxPageCount = 1; // 创建的页数最少要两页以上
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(new File(ORIG)));
        PdfSplitter pdfSplitter = new PdfSplitter(pdfDocument) {
            int partNumber = 1;
            @Override
            protected PdfWriter getNextPdfWriter(PageRange documentPageRange) {
                try {
                    return new PdfWriter(OUTPUT_FOLDER + "splitDocument_" + partNumber++ + ".pdf");
                } catch (final FileNotFoundException ignored) {
                    throw new RuntimeException();
                }
            }
        };
        //每次分的张数,
        pdfSplitter.splitByPageCount(maxPageCount, (pdfDoc, pageRange) -> pdfDoc.close());
        pdfDocument.close();
    }
}

另一种写法:

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PageRange;
import com.itextpdf.kernel.utils.PdfSplitter;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class MergeAndCount {
    public static final String DEST = "E:/pdf/myfiles/";
    public static final String RESOURCE = "E:/pdf/signed_out.pdf";
 
    public static void main(String[] args) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new MergeAndCount().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(final String dest) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(RESOURCE));
        List<PdfDocument> splitDocuments = new PdfSplitter(pdfDoc) {
            int partNumber = 1;
            @Override
            protected PdfWriter getNextPdfWriter(PageRange documentPageRange) {
                try {
                    return new PdfWriter(dest + "splitDocumentAfter_" + partNumber++ + ".pdf");
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }.splitBySize(200000);
        for (PdfDocument doc : splitDocuments) {
            doc.close();
        }
        pdfDoc.close();
    }
}

3、在指定位置插入新的PDF

import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
 
import java.io.File;
import java.io.IOException;
 
public class AddCover2 {
    public static final String DEST = "E:/pdf/copymerge/muilt_pdf2.pdf";
 
    public static final String COVER = "E:/pdf/global/spilt2.pdf";
    public static final String RESOURCE = "E:/pdf/copyres.pdf";
 
    public static void main(String[] args) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new AddCover2().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(RESOURCE), new PdfWriter(dest));
        PdfDocument cover = new PdfDocument(new PdfReader(COVER));

        PdfPageFormCopier formCopier = new PdfPageFormCopier();
        //插入页开始页,插入页结束页,被插入文档,被插入文档的插入位置,编译器
        //给定4   就是插入文件完成后第四页的位置
        cover.copyPagesTo(1, 1, pdfDoc, 4, formCopier);
 
        cover.close();
        pdfDoc.close();
    }
}

另一种写法:

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;
 
import java.io.File;
import java.io.IOException;
 
public class AddCover1 {
    public static final String DEST = "E:/pdf/copymerge/muilt_pdf1.pdf";  //合并文件地址
 
    public static final String COVER = "E:/pdf/signed_out.pdf";  //覆盖文件
    public static final String RESOURCE = "E:/pdf/copyres.pdf";  //源文件
 
    public static void main(String[] args) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new AddCover1().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws IOException {
    	//获得合并完成后pdf的输出地址
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        //获得覆盖的pdf文件        
        PdfDocument cover = new PdfDocument(new PdfReader(COVER));
        //获得被覆盖的文件
        PdfDocument resource = new PdfDocument(new PdfReader(RESOURCE));
 
        PdfMerger merger = new PdfMerger(pdfDoc);
        //指定要被覆盖的文件,起始页数,结束页数
        merger.merge(cover, 1, 3);
        merger.merge(resource, 3, resource.getNumberOfPages());
 
        cover.close();
        resource.close();
        merger.close();
    }
}

4、删除指定某一页的PDF

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.IOException;
//从pdf中删除某一页
public class PDFPageDeleter {
	//被删除文件
    private static final String ORIG = "E:/pdf/signed_out.pdf";
    //输出路径
    private static final String OUTPUT_FOLDER = "E:/pdf/myfiles/";

    public static void main(String[] args) throws IOException {
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(ORIG), new PdfWriter(OUTPUT_FOLDER + "after_deleted.pdf"));
        pdfDocument.removePage(2); //Note that as you remove a page the number of pages in your PDF will change
        pdfDocument.close();
    }
}

5、多个图片添加到一个PDF中

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;

import java.io.File;

public class MultipleImages {
	public static final String DEST = "E:/pdf/copyres.pdf";
	public static final String[] IMAGES = { "E:/pdf/logo.png", "E:/pdf/logo2.png","E:/pdf/logo3.png"};

	public static void main(String[] args) throws Exception {
		File file = new File(DEST);
		file.getParentFile().mkdirs();

		new MultipleImages().manipulatePdf(DEST);
	}

	protected void manipulatePdf(String dest) throws Exception {
		Image image = new Image(ImageDataFactory.create(IMAGES[0])); // 得到单个图像
		PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); // 获得被写入的PDF文件

		Document doc = new Document(pdfDoc, new PageSize(image.getImageWidth(), image.getImageHeight()));

		 for (int i = 0; i < IMAGES.length; i++) { image = new
		 Image(ImageDataFactory.create(IMAGES[i])); pdfDoc.addNewPage(new
		 PageSize(image.getImageWidth(), image.getImageHeight()));
		 image.setFixedPosition(i + 1, 0, 0); doc.add(image); 
		 }
		 doc.close();
	}
}

6、在页面中剪切和粘贴内容

import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
 
import java.io.File;
import java.io.IOException;
 
public class CutAndPaste {
    public static final String DEST = "X:/pdf/merge/page229_cut_paste.pdf";
    public static final String SRC = "x:/pdf/page229.pdf";
 
    public static void main(String[] args) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new CutAndPaste().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws IOException {
        PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
        Rectangle pageSize = srcDoc.getFirstPage().getPageSize();
        PdfDocument resultPdfDoc = new PdfDocument(new PdfWriter(dest));
        resultPdfDoc.setDefaultPageSize(new PageSize(pageSize));
        resultPdfDoc.addNewPage();
 
        PdfFormXObject pageXObject = srcDoc.getFirstPage().copyAsFormXObject(resultPdfDoc);
        Rectangle toMove = new Rectangle(100, 500, 100, 100);
 
        // Create a formXObject of a page content, in which the area to move is cut.
        PdfFormXObject formXObject1 = new PdfFormXObject(pageSize);
        PdfCanvas canvas1 = new PdfCanvas(formXObject1, resultPdfDoc);
        canvas1.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());
        canvas1.rectangle(toMove);
 
        // This method uses the even-odd rule to determine which regions lie inside the clipping path.
        canvas1.eoClip();
        canvas1.endPath();
        canvas1.addXObject(pageXObject, 0, 0);
 
        // Create a formXObject of the area to move.
        PdfFormXObject formXObject2 = new PdfFormXObject(pageSize);
        PdfCanvas canvas2 = new PdfCanvas(formXObject2, resultPdfDoc);
        canvas2.rectangle(toMove);
 
        // This method uses the nonzero winding rule to determine which regions lie inside the clipping path.
        canvas2.clip();
        canvas2.endPath();
        canvas2.addXObject(pageXObject, 0, 0);
 
        PdfCanvas canvas = new PdfCanvas(resultPdfDoc.getFirstPage());
        canvas.addXObject(formXObject1, 0, 0);
 
        // Add the area to move content, shifted 10 points to the left and 2 points to the bottom.
        canvas.addXObject(formXObject2, -20, -2);
 
        srcDoc.close();
        resultPdfDoc.close();
    }
}

7、将一个PDF文件替换成另一个指定页码的PDF的实现

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PageRange;
import com.itextpdf.kernel.utils.PdfSplitter;

//从别的PDF中替换当前PDF文件对应的页面
public class MergePDFBypageFromOhterPDF {

	public static void main(String[] args) {
		//pdf地址
		final String spiltPDFPath ="X:/pdf/test/signed_out.pdf";
		final String outPutSpiltPath ="X:/pdf/test/spiltPDF/";
		final String deleteTargetPDFPath ="X:/pdf/test/deleteTarget.pdf";
		final String outPutDeletedPath ="X:/pdf/test/merge/";
		try {
			replaceFromOtherPDFByPage(spiltPDFPath,outPutSpiltPath,deleteTargetPDFPath,outPutDeletedPath,3,5);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param spiltPDFPath  分割文件PDF路径
	 * @param outPutSpiltPath  分割PDF保存路径
	 * @param deleteTargetPDFPath  被删除PDF路径
	 * @param outPutDeletedPath   删除后PDF的保存路径
	 * @param insertPageNum  指定分割后插入的页码
	 * @param deletePageNum  指定删除页码也是插入页码
	 * @throws IOException
	 */
	public static void replaceFromOtherPDFByPage(String spiltPDFPath, final String outPutSpiltPath,
			String deleteTargetPDFPath,String outPutDeletedPath,int insertPageNum,int deletePageNum) throws IOException {
		//给定替换的单张PDF
		//获取需要制定分割的PDF文件的路径
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(spiltPDFPath));
        List<PdfDocument> splitDocuments = new PdfSplitter(pdfDoc) {
        	//指定分页大小
        	int pageNumber = 1;
            protected PdfWriter getNextPdfWriter(PageRange documentPageRange) {
                try {
                    return new PdfWriter(outPutSpiltPath + "splitDocumentAfter_" + pageNumber++ + ".pdf");
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }.splitBySize(200000);
        for (PdfDocument doc : splitDocuments) {
            doc.close();
        }
        pdfDoc.close();
		//删除指定页
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(deleteTargetPDFPath), new PdfWriter(outPutDeletedPath + "after_deletedPDF.pdf"));
        pdfDocument.removePage(deletePageNum); 
        pdfDocument.close();
        //指定页数插入
        //被插入的目标pdf文件
        PdfDocument trargetPDFDoc = new PdfDocument(new PdfReader(outPutDeletedPath + "after_deletedPDF.pdf" ), new PdfWriter(outPutDeletedPath + "MergePDF.pdf"));
        //插入pdf目标文件
        PdfDocument cover = new PdfDocument(new PdfReader(outPutSpiltPath + "splitDocumentAfter_" + insertPageNum + ".pdf")); 
        PdfPageFormCopier formCopier = new PdfPageFormCopier();
        //插入页开始页,插入页结束页,被插入文档,被插入文档的插入位置,编译器
        cover.copyPagesTo(1, 1, trargetPDFDoc, deletePageNum, formCopier);
        cover.close();
        trargetPDFDoc.close();
	}

}

更多实例参考请阅读官方Demo:https://itextpdf.com/en/resources

你可能感兴趣的:(ITextPDF,7)