baidu_28081035
家明君
2020-07-14 11:33

Itext2 pdf 表格怎么添加 checkbox?

  • java

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

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条回答