java 利用Adobe模板生成pdf文件

1.引用的jar
  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
  </dependency>

  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.6</version>
  </dependency>import java.io.ByteArrayOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;/**
 * Created by znh on 2020/03/16.
 */
public class PdfUtils {
    protected static final Logger logger = LoggerFactory
            .getLogger(PdfUtils.class);
    
    /**
     * @param map
     * @param templatePath
     * @param newPDFPath
     * @param baseFont
     */
    @SuppressWarnings("unchecked")
    public static void pdfout(Map<String,Object> map,String templatePath,String newPDFPath,String baseFont) throws Exception{
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            //设置字体
            BaseFont bf = BaseFont.createFont(baseFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板  
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.setGenerateAppearances(true);
            //文字类的内容处理
            Map<String,String> datemap = (Map<String,String>)map.get("datemap");
            for(String key : datemap.keySet()){
                form.setFieldProperty(key, "textfont", bf, null);
           }
            for(String key : datemap.keySet()){
                String value = datemap.get(key);
                form.setField(key,value);
            }
          
            //图片类的内容处理
            Map<String,String> imgmap = (Map<String,String>)map.get("imgmap");
            if(null != imgmap){
                for(String key : imgmap.keySet()) {
                    String imgpath = imgmap.get(key);
                    if(Util.isNotEmpty(imgpath)){
                        int pageNo = form.getFieldPositions(key).get(0).page;
                        Rectangle signRect = form.getFieldPositions(key).get(0).position;
                        float x = signRect.getLeft();
                        float y = signRect.getBottom();
                        //根据路径读取图片
                        Image image = Image.getInstance(imgpath);
                        //获取图片页面
                        PdfContentByte under = stamper.getOverContent(pageNo);
                        //图片大小自适应
                        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                        //添加图片
                        image.setAbsolutePosition(x, y);
                        under.addImage(image);
                    }
                }
            }
            stamper.setFormFlattening(false);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            //pdf模版的页数
            int pagecount= reader.getNumberOfPages();
            for(int i=1 ;i<pagecount+1;i++){
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            doc.close();

        } catch (Exception e) {
           logger.info(e.getMessage());
           throw new Exception(e.getMessage());
        }
    }   
public static String getKeyValue(String key, String defaultval) { Properties props = new Properties(); InputStream inputStream = Util.class.getClassLoader().getResourceAsStream("setting.properties"); if (inputStream == null) { return null; } try { props.load(new InputStreamReader(inputStream,"UTF-8")); inputStream.close(); String value = props.getProperty(key, defaultval); return value; } catch (IOException e) { e.printStackTrace(); } return null; } /** * @param map * @param fileName * @throws Exception */ public static ImageObjectInfo archivalInfo(Map<String,Object> map,String fileName) throws Exception{
String templatePath = getKeyValue("elePolicytemplatePath", ""); String newPDFPath = getKeyValue("elePolicynewPDFPath", ""); String baseFont = getKeyValue("elePolicybaseFont", ""); logger.info("templatePath:"+templatePath); logger.info("baseFont:"+baseFont); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); newPDFPath += sdf.format(new Date()) + "/"; File dir = new File(newPDFPath); if (!dir.exists()) { dir.mkdirs(); } sdf = new SimpleDateFormat("MM-dd"); newPDFPath += sdf.format(new Date()) + "/"; dir = new File(newPDFPath); if (!dir.exists()) { dir.mkdirs(); } String times = DateFormat.convent_YYYYMMddHHmmss(new Date()); newPDFPath = newPDFPath + fileName + "_" + times + ".pdf"; logger.info("合成后的文件已输出到:" + newPDFPath); pdfout(map, templatePath, newPDFPath,baseFont); File f = new File(newPDFPath); ImageObjectInfo objectInfo = new ImageObjectInfo(); objectInfo.setPath(newPDFPath); objectInfo.setType("elePolicy"); objectInfo.setSize((int) f.length()); objectInfo.setFilename(fileName+"_"+times+".pdf"); logger.info(JSON.toJSONString(objectInfo)); return objectInfo; }
public static void main(String[] args) throws Exception { Map<String,String> map = new HashMap<String,String>(); map.put("name","张三"); map.put("areaName","浙江杭州"); map.put("idCard","330103197506020096"); map.put("cellphone","13120926315"); map.put("idCardDateE","2020-12-12"); map.put("education","大学本科"); map.put("practiceCode","45252525274525725725725725"); map.put("homeAddress","安徽省阜阳市颍东区别华办丰处梨树社区陈庄34亏1户"); Map<String,String> map2 = new HashMap<String,String>(); map2.put("agency_cardImagZ","C:\\1.jpg"); map2.put("agency_cardImagF","C:\\2.jpg"); map2.put("bankCardImg","C:\\3.jpg"); map2.put("educatImg","C:\\4.jpg"); Map<String,Object> o=new HashMap<String,Object>(); o.put("datemap",map); o.put("imgmap",map2); archivalInfo(o,"z啧啧啧"); } }
posted @ 2020-04-09 11:13  无影-  阅读(497)  评论(0)    收藏  举报