通过Adobe Acrobat DC和iText.jar完成通过pdf模板生成pdf

iText也可以结合着工具来完成pdf绘制,可以往Adobe Acrobat DC生成的pdf模型进行填值。

通知书类似的pdf可以使用该方法进行绘制,只需要将pdf模型提前设定好,这样一般来说可以做的更漂亮。

代码如下:

package com.test;

import java.io.*;
import java.util.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class TestPrintPdf{
    public static void main(String[] args)throws Exception{
        System.out.println("begin");
        TestPrintPdf.test();
    }
    /**
    *测试方法
    */
    public static void test()throws IOException,DocumentException{
        //pdf模板
        System.out.println("come test");
        //这是我自己的测试路径,即模板pdf的路径
        String pdfPath="C:\\Users\\Administrator.SC-201606041031\\Desktop\\test\\javaitem\\file\\pdfModel.pdf";
        PdfReader pr = new PdfReader(pdfPath);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        //生成的pdf目标文件
        PdfStamper ps = new PdfStamper(pr,bos);
        //?
        PdfContentByte under = ps.getUnderContent(1);
        //字体
        BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> list = new ArrayList<BaseFont>();
        list.add(bf);
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(list);
        fillData(fields,preData());
        //设置属性生成文档
        ps.setFormFlattening(true);
        ps.close();

        //生成的pdf的文件路径
        String resultPath = "C:\\Users\\Administrator.SC-201606041031\\Desktop\\test\\javaitem\\file\\result.pdf";
        OutputStream os = new FileOutputStream(resultPath);
        os.write(bos.toByteArray());
        os.flush();
        os.close();
        bos.close();
    }
    /**
    *填充数据
    */
    public static void fillData(AcroFields fields,Map map)throws IOException,DocumentException{
        System.out.println("come fillData");
        //将map中的数据填充至fields中
        for(Object key:map.keySet()){
            fields.setField(key.toString(),map.get(key).toString());
        }
    }
    /**
    *测试数据
    */
    public static Map<String,String> preData(){
        System.out.println("come preData");
        Map map = new HashMap();
        map.put("name","张三");
        map.put("age","20");
        return map;
    }
}


猜你喜欢

转载自blog.csdn.net/csdn15679160266/article/details/81055266