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

  • Post author:
  • Post category:其他




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



版权声明:本文为weixin_42832953原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。