添加表单元素与iTextSharp的表 [英] Adding form elements to a table with iTextSharp

查看:221
本文介绍了添加表单元素与iTextSharp的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个PDF文件,基本上是在一个表格式的用户列表。我需要的表有复选框在里面。到目前为止,我有表和单独的复选框,但我不能找到一种方式来获得该表中的复选框。我想我需要使用AddCell()方法将它们添加



下面是我的代码:

 静态无效的主要(字串[] args)
{
//创建文档,文件流,作家
文档的文档=新的文件(PageSize.LETTER);
的FileStream文件=新的FileStream(@C:\Users\test\User List.pdf,FileMode.OpenOrCreate);
PdfWriter作家= PdfWriter.GetInstance(文件,档案);


{
//元
doc.AddAuthor(测试用户);
doc.AddCreator(测试文档);
doc.AddKeywords(测试文档);
doc.AddSubject(测试文档);
doc.AddTitle(测试文档 - 测试用户);

//打开PDF文档
doc.Open();

PdfContentByte CB = writer.DirectContent;
字体_bf =新字体(Font.FontFamily.HELVETICA,9);

//创建一个表
PdfPTable表=新PdfPTable(3);
PdfPCell电池=新PdfPCell(新词(用户列表));

PdfFormField场= PdfFormField.CreateCheckBox(作家);
field.SetWidget(新的Rectangle(40,500,60,530),PdfAnnotation.HIGHLIGHT_INVERT);
field.SetFieldFlags(PdfAnnotation.FLAGS_PR​​INT);
field.FieldName =删除;
writer.AddAnnotation(场);

cell.Colspan = 3;
cell.Horizo​​ntalAlignment = 0; // 0 =左侧,1 =中心2 =右
cell.VerticalAlignment = 1;
table.AddCell(无);
table.AddCell(用户);
table.AddCell(删除);

//创建表单域
PdfAppearance [] = ONOFF新PdfAppearance [2];
矩形RECT;
PdfFormField复选框;
RadioCheckField _checkbox;

ONOFF [0] = cb.CreateAppearance(10,10);
ONOFF [0] .Rectangle(1,1,8,8);
ONOFF [0] .Stroke();

ONOFF [1] = cb.CreateAppearance(10,10);
ONOFF [1] .SetRGBColorFill(255,128,128);
ONOFF [1] .Rectangle(1,1,8,8);
ONOFF [1] .FillStroke();
ONOFF [1] .MoveTo(1,1);
ONOFF [1] .LineTo(9,9);
ONOFF [1] .MoveTo(1,9);
ONOFF [1] .LineTo(9,1);
ONOFF [1] .Stroke();

的for(int i = 0;我小于5;我++)
{
table.AddCell(i.ToString());
table.AddCell(用户+ I);
// RECT =新的Rectangle(400,675 - 我* 40,415,663 - 我* 40);
RECT =新的Rectangle(400,735 - 我* 40,415,723 - 我* 40);
_checkbox =新RadioCheckField(作家,矩形,用户+(I + 1),是);
=复选框_checkbox.CheckField;
checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL,关,开关机[0]);
checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL,开,开关机[1]);
writer.AddAnnotation(复选框);

//这就是我想加()的复选框表
//我可以添加到AddCell使复选框显示出来?
table.AddCell();
//ColumnText.ShowTextAligned(cb,Element.ALIGN_LEFT,新词(用户+(I + 1),_bf),50,665 - 我* 40,0);
}

CB = writer.DirectContent;
doc.Add(表);

}
赶上(DocumentException DEX)
{
掷(DEX);
}
终于
{
//关闭
doc.Close();
writer.Close();
file.Close();
}
}



有没有办法做到这一点使用iTextSharp的?也许有更好的库使用


解决方案

我要引用的 iText的网站展示如何将现场传递给定制 IPdfPCellEvent 实施和< A HREF =htt​​p://itextpdf.com/examples/iia.php?id=162相对=nofollow>如何创建该自定义类,并在C#下面创建它。



首先,创建一个类的工具在 IPdfPCellEvent



<$ p $要添加IPdfPCellEvent {
/ **父其中一个子领域有着领域:p> 公共类ChildFieldEvent。 * /
保护PdfFormField父母;
/ **具有无以复加* /
子字段保护PdfFormField孩子;
/ **单元* /
保护浮填充内部的磁场的填充;

/ **
*创建一个ChildFieldEvent。
*参数父父字段
*参数小子子字段
*参数填充的填充
* /
公共ChildFieldEvent(PdfFormField父母,孩子PdfFormField ,浮填充){
this.parent =父母;
this.kid =孩子;
this.padding =填充;
}

/ **
*的子字段添加到母体,并设置子场的坐标。
* /
公共无效CellLayout(PdfPCell细胞,iTextSharp.text.Rectangle RECT,PdfContentByte [] CB){
parent.AddKid(孩子);
kid.SetWidget(新iTextSharp.text.Rectangle(
rect.GetLeft(填充),
rect.GetBottom(填充),
rect.GetRight(填充),
rect.GetTop(填充)

PdfAnnotation.HIGHLIGHT_INVERT
);
}
}



然后,只需设置 CellEvent 上应该有他们的任何领域的细胞。

  //文件创建
VAR TESTFILE = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)的test.pdf);使用

//标准的PDF创建,这里没有什么特别使用
(VAR FS =新的FileStream(TESTFILE,FileMode.Create,FileAccess.Write,FileShare.None)){
(VAR DOC =新的文件()){
使用(VAR作家= PdfWriter.GetInstance(DOC,FS)){
doc.Open();

//创建一个根表单对象,我们将添加孩子来。这样,我们就不必每一个子的注释添加到写入
变种根= PdfFormField.CreateEmpty(作家);
root.FieldName =根;

//创建一个两列的表
变种T =新PdfPTable(2);

//添加一个基本的
t.AddCell(名);

//创建文本框我们,我们正在传递被忽略,没关系
变种TF =新的TextField(作家,新iTextSharp.text.Rectangle(0矩形, 0),直呼其名);

//创建一个新的细胞
细胞VAR =新PdfPCell();

//设置单元格的事件给我们的定制IPdfPCellEvent执行
cell.CellEvent =新ChildFieldEvent(根,tf.GetTextField(),1);

//单元格添加到我们的表
t.AddCell(单元);

//将表添加到文件
doc.Add(T);

//重要!根注解加入也增加了所有孩子的注解
writer.AddAnnotation(root)的作家;


//清理
doc.Close();
}
}
}


I'm trying to create a PDF document that is essentially a list of users in a table format. I need the table to have checkboxes in it. So far, I have the table and the checkboxes separately but I cannot find a way to get the checkboxes in the table. I think I need to add them using the AddCell() method.

Here is my code:

static void Main(string[] args)
    {
        // create the document, filestream, writer
        Document doc = new Document(PageSize.LETTER);
        FileStream file = new FileStream(@"C:\Users\test\User List.pdf", FileMode.OpenOrCreate);
        PdfWriter writer = PdfWriter.GetInstance(doc, file);

        try
        {
            // metadata
            doc.AddAuthor("Test User");
            doc.AddCreator("Test Document");
            doc.AddKeywords("Test Document");
            doc.AddSubject("Test Document");
            doc.AddTitle("Test Document - Test User");

            // open up the PDF document
            doc.Open();

            PdfContentByte cb = writer.DirectContent;
            Font _bf = new Font(Font.FontFamily.HELVETICA, 9);

            // create a table
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell = new PdfPCell(new Phrase("User List"));

            PdfFormField field = PdfFormField.CreateCheckBox(writer);
            field.SetWidget(new Rectangle(40, 500, 60, 530), PdfAnnotation.HIGHLIGHT_INVERT);
            field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
            field.FieldName = "Delete";
            writer.AddAnnotation(field);

            cell.Colspan = 3;
            cell.HorizontalAlignment = 0; //0 = left, 1 = center, 2 = right
            cell.VerticalAlignment = 1;
            table.AddCell("No.");
            table.AddCell("Users");
            table.AddCell("Delete");

            // create form fields
            PdfAppearance[] onOff = new PdfAppearance[2];
            Rectangle rect;
            PdfFormField checkbox;
            RadioCheckField _checkbox;

            onOff[0] = cb.CreateAppearance(10, 10);
            onOff[0].Rectangle(1, 1, 8, 8);
            onOff[0].Stroke();

            onOff[1] = cb.CreateAppearance(10, 10);
            onOff[1].SetRGBColorFill(255, 128, 128);
            onOff[1].Rectangle(1, 1, 8, 8);
            onOff[1].FillStroke();
            onOff[1].MoveTo(1, 1);
            onOff[1].LineTo(9, 9);
            onOff[1].MoveTo(1, 9);
            onOff[1].LineTo(9, 1);
            onOff[1].Stroke();

            for (int i = 0; i < 5; i++)
            {
                table.AddCell(i.ToString());
                table.AddCell("User " + i);
                //rect = new Rectangle(400, 675 - i*40, 415, 663 - i*40);
                rect = new Rectangle(400, 735 - i * 40, 415, 723 - i * 40);
                _checkbox = new RadioCheckField(writer, rect, "User "+(i+1), "Yes");
                checkbox = _checkbox.CheckField;
                checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]);
                checkbox.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1]);
                writer.AddAnnotation(checkbox);

                // this is where I am trying to add the checkbox to the table
                // what can I add to AddCell() to make the checkbox show up?
                table.AddCell();
                //ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("User " + (i + 1), _bf), 50, 665 - i * 40, 0);
            }

            cb = writer.DirectContent;
            doc.Add(table);

        }
        catch(DocumentException dex)
        {
            throw (dex);
        }
        finally
        {
            // close
            doc.Close();
            writer.Close();
            file.Close();
        }
    }

Is there any way to do this using iTextSharp? Maybe there is a better library to use?

解决方案

I'll reference the iText website showing how to pass a field to a custom IPdfPCellEvent implementation and how to create that that custom class and recreate it below in C#.

First, create a class the implements the IPdfPCellEvent:

public class ChildFieldEvent : IPdfPCellEvent {
    /** A parent field to which a child field has to be added. */
    protected PdfFormField parent;
    /** The child field that has to be added */
    protected PdfFormField kid;
    /** The padding of the field inside the cell */
    protected float padding;

    /**
     * Creates a ChildFieldEvent.
     * @param parent the parent field
     * @param kid the child field
     * @param padding a padding
     */
    public ChildFieldEvent(PdfFormField parent, PdfFormField kid, float padding) {
        this.parent = parent;
        this.kid = kid;
        this.padding = padding;
    }

    /**
     * Add the child field to the parent, and sets the coordinates of the child field.
     */
    public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] cb) {
        parent.AddKid(kid);
        kid.SetWidget(new iTextSharp.text.Rectangle(
                                                    rect.GetLeft(padding),
                                                    rect.GetBottom(padding),
                                                    rect.GetRight(padding),
                                                    rect.GetTop(padding)
                                                    ),
                                                    PdfAnnotation.HIGHLIGHT_INVERT
                                                    );
    }
}

Then just set the CellEvent on any cells that should have fields in them.

//File to create
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");

//Standard PDF creation, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();

            //Create a root form object that we'll add "children" to. This way we don't have to add each "child" annotation to the writer
            var root = PdfFormField.CreateEmpty(writer);
            root.FieldName = "root";

            //Create a two column table
            var t = new PdfPTable(2);

            //Add a basic cell
            t.AddCell("First Name");

            //Create our textfield, the rectangle that we're passing in is ignored and doesn't matter
            var tf = new TextField(writer, new iTextSharp.text.Rectangle(0, 0), "first-name");

            //Create a new cell
            var cell = new PdfPCell();

            //Set the cell event to our custom IPdfPCellEvent implementation
            cell.CellEvent = new ChildFieldEvent(root, tf.GetTextField(), 1);

            //Add the cell to our table
            t.AddCell(cell);

            //Add the table to the document
            doc.Add(t);

            //IMPORTANT! Add the root annotation to the writer which also adds all of the child annotations
            writer.AddAnnotation(root);


            //Clean up
            doc.Close();
        }
    }
}

这篇关于添加表单元素与iTextSharp的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆