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

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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记