多个PDF合并到一个PDF

时间:2021-03-21 19:57:56

依赖的jar包如下:

itext-2.1.7.jar
itext-xtra-5.1.3.jar
itextpdf-5.1.3.jar


示例代码如下:

/*******************************************************************************
 * @project: Capital-AVIDM4
 * @package: com.acconsys.avidm4.utils
 * @file: PDFUtils.java
 * @author: Fionn
 * @created: 2013-3-25
 * @purpose:
 * 
 * @version: 1.0
 * 
 * Revision History at the end of file.
 * 
 * Copyright 2013 AcconSys All rights reserved.
 ******************************************************************************/

/**
 * 
 */

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

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;

public class PDFUtils {

	public static void main(String[] args) {
		File[] pdfs = new File[2];
		pdfs[0] = new File("C:/CHS-AVIDM4/Design1/A/Diagram1.pdf");
		pdfs[1] = new File("C:/CHS-AVIDM4/Design1/A/Diagram2.pdf");
		File mergedPdf = new File("C:/CHS-AVIDM4/Design1/A/MergedDiagram1.pdf");
		try {
			merge(pdfs, mergedPdf);
		} catch (IOException | DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param pages
	 * @param pdffile
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void merge(File[] pages, File pdffile) throws IOException,
			DocumentException {
		if (!pdffile.exists()) {
			pdffile.createNewFile();
		}
		System.out.println(pages.length);
		if (pages.length < 1)
			return;

		Document document = new Document(new PdfReader(
				((File) pages[0]).getAbsolutePath()).getPageSize(1));
		PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdffile));
		document.open();
		for (int i = 0; i < pages.length; i++) {
			PdfReader reader = new PdfReader((pages[i]).getAbsolutePath());
			int num = reader.getNumberOfPages();
			for (int j = 1; j <= num; j++) {
				document.newPage();
				PdfImportedPage page = copy.getImportedPage(reader, j);
				copy.addPage(page);
			}
		}
		System.out.println("----------------------------------");
		document.close();
		// for (File page : pages) {
		// page.deleteOnExit();
		// }
	}

}

/*******************************************************************************
 * <B>Revision History</B><BR>
 * [type 'revision' and press Alt + / to insert revision block]<BR>
 * 
 * 
 * 
 * Copyright 2013 AcconSys All rights reserved.
 ******************************************************************************/
 
示例代码下载位置如下:
百度云下载链接:
http://pan.baidu.com/s/1kVMe4gZ 密码:zrl8
或者csdn下载:
http://download.csdn.net/download/zp357252539/9969990