Ricardo·M·Smile 2020-07-14 11:33 采纳率: 75%
浏览 717
已采纳

Itext2 pdf 表格怎么添加 checkbox?

需要效果如图:
图片说明
在官网找到如下方法生成效果如下:
图片说明
代码如下:

public void createPDf() throws IOException, DocumentException {
        //创建文档对象
                // 指定页面大小为A4
        Document document =new Document(PageSize.A4); 

        //获取PdfWriter实例
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\Users\ThinkStation\Desktop\logs\test.pdf"));

        //打开文档
        document.open();

        PdfFormField checkBox = PdfFormField.createCheckBox(writer);

        checkBox.setFieldName("Language");
        checkBox.setAppearanceState("a");


        PdfPTable table = new PdfPTable(3);

        // add cells
        PdfPCell cell = new PdfPCell(new Phrase("abc"));

        table.addCell(cell);

        PdfPCell cell1 = new PdfPCell();

        cell1.setCellEvent(new MyCellField(checkBox, "a"));

        table.addCell(cell1);

        PdfPCell cell13 = new PdfPCell();

        cell13.setCellEvent(new MyCellField(checkBox, "b"));

        table.addCell(cell13);


        document.add(table);

        writer.addAnnotation(checkBox);

        //AJZ_XCWH_Template(document,writer);

        //关闭文档
        document.close();
    }

    public class MyCellField implements PdfPCellEvent {
        protected PdfFormField radiogroup;
        protected String value;
        public MyCellField(PdfFormField radiogroup, String value) {
            this.radiogroup = radiogroup;
            this.value = value;
        }

        public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[]  canvases) {
            final PdfWriter writer = canvases[0].getPdfWriter();
            RadioCheckField radio = new RadioCheckField(writer, rectangle, null, value);

            try {
                radiogroup.addKid(radio.getCheckField());
            } catch (final IOException ioe) {
                throw new ExceptionConverter(ioe);
            } catch (final DocumentException de) {
                throw new ExceptionConverter(de);
            }
        }
    }

其实在其他博客上还有一种类似的方法可以达到效果如:
https://blog.csdn.net/Donald_Draper/article/details/88307007

是否还有更加合适方式,希望可以获得一些指点,谢谢。
Ps:查文档发现
radio.setCheckType(RadioCheckField.TYPE_CHECK);
可以改变默认样式。

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-07-14 14:39
    关注

    如果你不是表单,只是输出,直接用特殊符号就可以。方块,方块打构,在字库中都有

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵