1. 程式人生 > >itext生成發票套打(操作PDF)

itext生成發票套打(操作PDF)

1.用Adobe Acrobat操作pdf

首先用Adobe Acrobat 在檔案上新增文字域,表單>新增或編輯域>文字域,如圖添加了兩個文字域,名稱分別是city,name
在這裡插入圖片描述

java程式碼

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

	public void Invoice(){
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {
            String pdfTemplate = "D://bb.pdf";
            PdfReader reader = new PdfReader(pdfTemplate);
            PdfStamper stamper = new PdfStamper(reader, ba);
 //           Image img = Image.getInstance("/Users/me/Documents/順豐速遞快遞單.jpg");
 //           img.setAbsolutePosition(0,0);
 //           img.scaleToFit(reader.getPageSize(1));
            PdfContentByte under = stamper.getUnderContent(1);
//            under.addImage(img,img.getScaledWidth(),0,0,img.getScaledHeight(),0,0);
//            under.addImage(img);
            //使用中文字型
            BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //取出所有欄位
            AcroFields form = stamper.getAcroFields();
            form.addSubstitutionFont(bf);
            //為欄位賦值
            form.setField("name", "高偉");
            form.setField("city", "小蒼");
            stamper.setFormFlattening(true);

            stamper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        response.setContentType("application/pdf");
//        resp.setHeader("Content-disposition", "attachment; filename=report.pdf");
        response.setContentLength(ba.size());
        try {
			ServletOutputStream out = response.getOutputStream();
			ba.writeTo(out);
			out.flush();
			out.close();
			ba.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("A Document error:" + e.getMessage()); 
		}
	}

在瀏覽器訪問該action(servlet):
在這裡插入圖片描述

需要jar包:
itext-asian-5.2.0.jar
itextpdf-5.4.2.jar
操作pdf的工具:
Adobe Acrobat 9 Pro