![]() |
Third Party Products »
Product Showcase »
Components and Libraries
Intermediate
PDF Forms and JavaScript - 100% .NET Class LibraryBy Frank RemPDFKit.NET 2.0 is a 100% .NET component written entirely in C# for creating, manipulating and reading PDF documents and PDF forms. This article will focus on the form and JavaScript features of PDFKit.NET 2.0. I will show how to fill existing forms, create new forms and add client-side JavaScript. |
C#, Windows, .NET 1.1, .NET 2.0VS.NET2003, VS2005, Dev
|
|
Advanced Search |
|
|
|
PDFKit.NET 2.0 is a 100% .NET component written entirely in C# for creating, manipulating and reading PDF documents and PDF forms. In this article, I will concentrate on the form and JavaScript features of PDFKit.NET 2.0. I will show how to fill existing forms, create new forms and add client-side JavaScript.
| Create PDF forms (new) | Just like you can add text, you can add form fields like text fields, check boxes, etc. You can also add actions and scripts to form fields. |
| Actions (new) | Read, create and modify actions. Action types include executing JavaScript, submitting a form, jumping to a page, launching an application and more. |
| JavaScript (new) | Validation and formatting JavaScript are executed when you assign a value to a field. |
| Bookmarks (new) | Read, create and modify bookmarks. You can format bookmark items and assign actions and modify existing bookmark actions. |
| LiveCycle Designer (new) | Consume static XFA forms. Producing XFA forms and consuming dynamic XFA forms is not supported. |
| Text extraction (new) | Extract text as a collection of glyphs. Per glyph you can retrieve the position, font size, font and Unicode value. |
| Digital signatures (new) | Digitally sign PDF documents (multiple signing supported) and verify digitally signed PDF documents. |
| Barcodes (new) | Create 1D (Code 128; Code 2 of 5; Code 3 of 9) and 2D (PDF417) barcodes. |
| Split and Append | create a new document; get single or multiple pages from an existing PDF document; combine existing and new page to create a new document |
| Form filling | (multiline) text fields, check boxes, radio button, list boxes and combo boxes, read position and size of fields, flatten, remove or preserve fields |
| Security / Encryption | 40 and 128 bit encryption; consume encrypted documents; set user and owner password; set user privileges such as allow print/copy |
| Stamping | multiline text (alignment, justification, multiple fonts, etc); hyperlinks; primitive shapes such as Line, Pie, Rectangle, Image; position, rotate and scale shapes |
| General | write to disk, memory or directly to an HTTP response; read from disk or memory; constant, low memory consumption, independent of document size |
In this article, I will concentrate on the form and JavaScript features of PDFKit.NET 2.0. I will show how to fill existing forms, create new forms and add client-side JavaScript.
All fields in a PDF document can be accessed through the Document.Fields property. It returns an instance of type TallComponents.PDF.Forms.Fields.FieldCollection. The items in this collection are derived instances of type Field and can be retrieved by a 0-based index or a full field name. This collection is modifiable, meaning that you can also add and remove fields.
A widget is an annotation that provides the visual representation of a field. It allows the user to interact with the field, e.g. to enter text or select a radio button. In general, a field can have multiple widgets but in most cases it only has one. It is important to understand that a field is contained by a document and a widget is contained by a page. It is the field that holds the value. All widgets of a field show that single value.
The following figure illustrates the relation between document, field, page and widget:
The following code sample shows how to programmatically open a form, retrieve a text field by name, fill the text field and then save the form.
// open an existing form
using (FileStream fileIn = new FileStream("in.pdf", FileMode.Open,
FileAccess.Read))
{
Document document = new Document(fileIn);
// retrieve field
TextField textField = (TextField) document.Fields["firstName"];
// fill text field
textField.Value = "Frank";
// save the form to a new file
using (FileStream fileOut = new FileStream("out.pdf", FileMode.Create,
FileAccess.Write))
{
document.Write(fileOut);
}
}
Although this code sample uses file streams, PDFKit.NET supports any System.IO.Stream. So it is possible to read and write PDF documents to memory streams (e.g. to store PDFs as blobs in a database) or write to an HTTP response stream without any disk access.
In this section I will create a PDF form from scratch entirely in code. The form has three text fields: A, B and SUM and a single button: ADD. When the user opens the created PDF in a PDF reader and fills fields A and B and hits the ADD button, JavaScript will be invoked that fills field SUM with the sum of A and B.
The following code creates the form:
// create a new document with 0 pages
Document document = new Document();
// add a new empty page to the document
Page page = new Page(PageSize.A6, true);
document.Pages.Add(page);
// add 3 text fields and a button - see helper methods below
addTextField(document, page, "A", 20);
addTextField(document, page, "B", 80);
addButton(document, page, "ADD", 140);
addTextField(document, page, "SUM", 200);
// add JavaScript to the push button
PushButtonField addField = document.Fields["ADD"] as PushButtonField;
addJavaScript( addField );
// save the new form
using (FileStream fileOut = new FileStream(@"..\..\newform.pdf",
FileMode.Create, FileAccess.Write))
{
document.Write(fileOut);
}
The code above uses three helper methods. Let's discuss them in turn.
The helper method addTextField adds a new text field. As you can see from the code, it first adds a new TextField instance to the Document.Fields collection, next it adds a new Widget instance to the Page.Widgets collection. By adding the Widget to the Field.Widgets collection, the Field and the Widget are connected. All other code has to do with positioning and styling the field appearance. Here is the code:
static void addTextField(Document document, Page page, string name, int left)
{
// create a new text field and add it the document
TextField field = new TextField(name);
document.Fields.Add(field);
// create a widget for the field and add it to the page
Widget widget = new Widget();
field.Widgets.Add(widget);
page.Widgets.Add(widget);
// position the widget
widget.Left = left;
widget.Bottom = 200;
widget.Width = 50;
widget.Height = 20;
// style the widget
widget.Font = Font.Helvetica;
widget.FontSize = 0; // autosize
widget.BorderWidth = 2;
widget.BorderStyle = TallComponents.PDF.Annotations.BorderStyle.Solid;
widget.BorderColor = RgbColor.Black;
}
The helper method addButton is not much different from addTextField. It first adds a new PushButtonField instance to the Document.Fields collection, next it adds a new PushButtonWidget instance to the Page.Widgets collection. Next, the widget is connected to the field by adding the widget to the Field.Widgets collection. All other code has to do with positioning and styling the field appearance. Here is the code:
static void addButton(Document document, Page page, string name, int left)
{
// create a push button field and add it the document
PushButtonField field = new PushButtonField(name);
document.Fields.Add(field);
// create a new widget for the field and add it to the page
PushButtonWidget widget = new PushButtonWidget();
field.Widgets.Add(widget);
page.Widgets.Add(widget);
// position the widget
widget.Left = left;
widget.Bottom = 200;
widget.Width = 50;
widget.Height = 20;
// style the widget
widget.Label = "ADD"; // button text
widget.Font = Font.Helvetica;
widget.FontSize = 0; // autosize
widget.BorderStyle = TallComponents.PDF.Annotations.BorderStyle.Beveled;
widget.BorderColor = RgbColor.Black;
}
The implementation of helper method addJavaScript is straightforward. It first retrieves the widget from the field that is passed as an argument. Next it creates a JavaScript action. The JavaScriptAction is assigned to the widget.MouseUpActions collection. This tells the PDF reader to execute this action when the mouse is released after pressing the button.
Finally, the JavaScript action is assigned a snippet of JavaScript which is quite straightforward. Here is the code:
static void addJavaScript( Field field )
{
// retrieve the widget
Widget widget = field.Widgets[0];
// create a new JavaScript action and associate it
// with the mouse-up event
JavaScriptAction action = new JavaScriptAction();
widget.MouseUpActions.Add(action);
// set the JavaScript
action.JavaScript.Text = "this.getField('SUM').value =
this.getField('A').value + this.getField('B').value;";
}
The widget.MouseUpActions collection can hold any type of action. PDF supports many more Action types. This is expressed by our object model by having an abstract base class Action from which all action types inherit directly or indirectly. Among them are GoToAction, UriAction, ResetFormAction, etc. All actions in the collection are executed in sequence.
Thanks for taking the time to read this article. At TallComponents we take great care to offer an object model that helps you write really simple, yet powerful client code. I hope we have succeeded in doing that. I am looking forward to comments and suggestions.
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 3 Mar 2008 Editor: Sean Ewington |
Copyright 2007 by Frank Rem Everything else Copyright © CodeProject, 1999-2009 Web15 | Advertise on the Code Project |