1. 程式人生 > >java根據模板生成pdf檔案並匯出(轉)

java根據模板生成pdf檔案並匯出(轉)

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

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

public class PDFCreate {
	// 利用模板生成pdf
	public static void fillTemplate() {
		// 模板路徑
		String templatePath = "pdf/協議3.pdf";
		// 生成的新檔案路徑
		String newPDFPath = "pdf/協議2.pdf";
		PdfReader reader;
		FileOutputStream out;
		ByteArrayOutputStream bos;
		PdfStamper stamper;
		try {
			out = new FileOutputStream(newPDFPath);// 輸出流
			reader = new PdfReader(templatePath);// 讀取pdf模板
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();//PDF表單

			String[] str = {  "15068298235","15068298235","421125199103152019", "高高高"};
			int i = 0;
			java.util.Iterator<String> it = form.getFields().keySet().iterator();
			while (it.hasNext()) {
				String name = it.next().toString();
				System.out.println(name);
				form.setField(name, str[i++]);
			}
			stamper.setFormFlattening(true);// 如果為false那麼生成的PDF檔案還能編輯,一定要設為true
			stamper.close();

			Document doc = new Document();
			PdfCopy copy = new PdfCopy(doc, out);
			doc.open();
			int count = reader.getNumberOfPages();//原PDF總頁數
			for(int j=1;j<=count;j++){
				PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), j);
				copy.addPage(importPage);
			}
			
			doc.close();

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

	}

	public static void main(String[] args) {
		fillTemplate();
	}
}