Itext填写pdf中的复选框对勾问题解决

首先用Acrobat Pro工具将复选框的样式修改成勾形;导出值设为true

 

data.put("self_way","true");将其设为true就可以啦
package com.pdf3;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.AcroFields.Item;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class PDFUtils {


    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if(formFields.containsKey(key)){
                String value = data.get(key);
                fields.setField(key, value,"true"); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        } //fields.setGenerateAppearances(true);

        Iterator<String> itemsKey = formFields.keySet().iterator();
        while(itemsKey.hasNext()){
            String itemKey = itemsKey.next();
           /* if (itemKey.contains("yes")){

            }*/
            if(!keys.contains(itemKey)){
                fields.setField(itemKey, " ");

            }
        }
    }

    /**
     * @param templatePdfPath
     *            模板pdf路径
     * @param generatePdfPath
     *            生成pdf路径
     * @param data
     *            数据
     */
    public static String generateChinesePDF(String templatePdfPath, String generatePdfPath, Map<String, String> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            PdfReader reader = new PdfReader(templatePdfPath);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            /* 使用中文字体 */
            // BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/seguisym.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);         
            //BaseFont bf = BaseFont.createFont("/Users/huangxiaogen/Downloads/seguisym.ttf", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setGenerateAppearances(true);
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data);
            /* 必须要调用这个,否则文档不会生成的  如果为false那么生成的PDF文件还能编辑,一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();
            fos = new FileOutputStream(generatePdfPath);
            fos.write(bos.toByteArray());
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }



    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String> checkData = new HashMap<String, String>();
        //key为pdf模板的form表单的名字,value为需要填充的值
      /*  data.put("title", "在线医院");
        data.put("case", "123456789");
        data.put("date", "2018.12.07");
        data.put("name", "gitbook");
        data.put("sex", "男");
        data.put("age", "29");
        data.put("phone", "13711645814");
        data.put("office", "内科");
        data.put("cert", "身痒找打");
        data.put("drug", "1、奥美拉唑肠溶胶囊             0.25g10粒×2板 ");
        data.put("dose", "×2盒");
        data.put("cons", "用法用量:口服 一日两次 一次2粒");
        data.put("tips", "温馨提示");
        data.put("desc", "尽量呆在通风较好的地方,保持空气流通,有利于病情康复。尽量呆在通风较好的地方");*/
        data.put("check_name", "张三");
        data.put("date", "2019-01-04");
     
        data.put("self_way","true");//复选框问题解决


        


        generateChinesePDF("c:/Downloads/1343.pdf",
                "c:/test1.pdf", data );




    }


}
iTextPDF是一个用于生成PDF文档的Java库,如果你想在PDF添加复选框,可以按照以下步骤操作: 1. **引入依赖**:首先,你需要在项目引入iTextPDF库,如果你使用Maven,可以在pom.xml文件添加如下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> <!-- 使用最新版本或根据实际情况更新 --> </dependency> ``` 2. **创建PdfPCell和PdfChunk**:复选框需要在PdfPCell创建,并作为PdfChunk的一部分添加到表格或页面上: ```java PdfPCell checkboxCell = new PdfPCell(new PdfPCellAlignment(Element.ALIGN_CENTER)); checkboxCell.setIndirectReference(PdfAction.getNamedAction("Check")); checkboxCell.setBorderWidth(0); checkboxCell.addElement(new PdfPCell Chunk.NEWLINE); ``` `PdfAction.getNamedAction("Check")` 是为了设置复选框的状态。 3. **创建表格**:在PdfPTable添加这个复选框单元格: ```java PdfPTable table = new PdfPTable(1); table.addCell(checkboxCell); ``` 4. **将表添加到文档**:最后,将创建好的PdfPTable添加到你的PdfDocument: ```java document.add(table); ``` 完整的示例代码片段可能会像这样: ```java PdfDocument document = new PdfDocument(); try { // 创建表格 PdfPTable table = new PdfPTable(1); PdfPCell checkboxCell = new PdfPCell(new PdfPCellAlignment(Element.ALIGN_CENTER)); checkboxCell.setIndirectReference(PdfAction.getNamedAction("Check")); checkboxCell.setBorderWidth(0); checkboxCell.addElement(new PdfPCell Chunk.NEWLINE); table.addCell(checkboxCell); // 添加复选框单元格 // 将表格添加到文档 document.add(table); // ...其他PDF内容... } finally { document.close(); // 关闭文档 } ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值