本文介绍如何使用C1PDF控件,从应用程序创建支持AcroForm的PDF文件。
C1PDF控件将内容添加到文档所使用的命令与.NET Graphics类中的命令类似。同时,PDF for .NET控件提供安全、压缩、大纲、超链接,以及附件等功能。
创建C1PdfDocument
首先从工具箱拖拽或是用code生成C1PdfDocument。生成代码如下:
private C1.C1Pdf.C1PdfDocument _c1pdf = new C1.C1Pdf.C1PdfDocument();
其次,将内容添加到PDF文档,这时候所使用的命令与在WinForms的Grphics类中的命令相似,它可以添加文本、图像、线条、矩形、椭圆、扇形、弧形、圆角矩形、多边形,贝塞尔曲线,以及更多。 可以参考C1PdfDocument的DrawString,DrawImage,DrawLine等方法。
C1PDF支持AcroForms
可以使用AddField方法将Acrobat表单字段添加到PDF文件。PDF for .NET控件支持如下字段类型:文本框、复选框、单选按钮、下压按钮、组合框、列表框,以及签名栏。在本文的Demo文件中,有对所有类型的支持代码。
现在用文本框举例,如果添加文本框到PDF文件,则需要:
首先创建文本框字段,代码如下:
// text box field rc = new RectangleF(rc.X, rc.Y + rc.Height / 10, rc.Width / 3, rc.Height / 30); PdfTextBox textBox1 = RenderTextBox("TextBox Sample", fieldFont, rc); textBox1.BorderWidth = FieldBorderWidth.Thick; textBox1.BorderStyle = FieldBorderStyle.Inset; textBox1.BorderColor = Color.Green;
然后把文本框字段使用AddField方法添加到PDF文档。具体代码如下:
// add text box field for fields of the PDF document // with common parameters and default names. // internal PdfTextBox RenderTextBox(string text, Font font, RectangleF rc, Color back, string toolTip) { // create string name = string.Format("ACFTB{0}", _textBoxCount + 1); PdfTextBox textBox = new PdfTextBox(); // default border //textBox.BorderWidth = 3f / 4; textBox.BorderStyle = FieldBorderStyle.Solid; textBox.BorderColor = SystemColors.ControlDarkDark; // parameters textBox.Font = font; textBox.Name = name; textBox.DefaultText = text; textBox.Text = text; textBox.ToolTip = string.IsNullOrEmpty(toolTip) ? string.Format("{0} ({1})", text, name) : toolTip; if (back != Color.Transparent && !back.IsEmpty) { textBox.BackColor = back; } // add _c1pdf.AddField(textBox, rc); _textBoxCount++; // done return textBox; } internal PdfTextBox RenderTextBox(string text, Font font, RectangleF rc, Color back) { return RenderTextBox(text, font, rc, back, null); } internal PdfTextBox RenderTextBox(string text, Font font, RectangleF rc) { return RenderTextBox(text, font, rc, Color.Transparent, null); }
保存PDF文档
最后可以保存在应用程序中生成的PDF文件,使用C1PdfDocument下的Save方法,保存在IO.Stream中或是保存在文件里。该方法如下所示:
// // 摘要: // Saves the Pdf document to a System.IO.Stream. public void Save(Stream stream); // // 摘要: // Saves the Pdf document to a file. public void Save(string fileName);
运行本文附件中的Demo,点击Form上的按钮,生成如下的PDF文档:
本文Demo的源代码如下: