yangys
2025-09-13 083df8d788c95c009a94378e620684eb5de2bd21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package org.springblade.mdm.commons.support;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
 
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;
 
/**
 * 模板生成pdf
 */
public class TemplatedPdfWriter {
    private byte[] templateBytes;
 
    public TemplatedPdfWriter(byte[] templateBytes){
        this.templateBytes = templateBytes;
    }
 
    public void setTemplateBytes(byte[] templateBytes){
        this.templateBytes = templateBytes;
    }
    public void write(Map<String,String> data, OutputStream outputStream) throws DocumentException, IOException {
 
        PdfReader reader = null;
        PdfStamper pdfStamper = null;
 
        reader = new PdfReader(this.templateBytes);
        pdfStamper =  new PdfStamper(reader, outputStream);
        // 使用中文字体
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<>();
        fontList.add(bf);
        AcroFields fields = pdfStamper.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        fillData(fields, data);//染
        //必须要调用这个,否则文档不会生成的
        pdfStamper.setFormFlattening(true);
        pdfStamper.close();
    }
 
    void fillData(AcroFields fields, Map<String, String> data) throws DocumentException, IOException {
 
        for (String key : data.keySet()) {
            String value = data.get(key);
            // 为字段赋值,注意字段名称是区分大小写的fields.setField(key,value);
            fields.setField(key,value,true);
 
            //form.setFieldProperty("fieldName", "clrflags", PdfAnnotation.FLAGS_HIDDEN, null);
            //fields.setFieldRichValue()
        }
 
    }
 
}