Fill in a template PDF document

Fill in a template PDF document

Fill in a template form for all instances in a database

This code sample shows you how you can import a template document and fill it in with data from a database. This can be used for example for salary slips, where you create a template with fields for employee firstname, last name, salary etc. etc. after which you can fill the fields with data from a database; all in one go!

In the following image you can see the fields in the resulting PDF, notice how they have been flattened and cannot be altered anymore by the user.

Append Template

string[] names = {  "Robert", "Stam",
                    "Frank", "Rem",
                    "Marnix", "van Valen",
                    "Marco", "Kesseler" };

//open the template document
using (FileStream templateStream = new FileStream(@"..\..\template.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
    Document templateDoc = new Document(templateStream);

    Page templatePage = templateDoc.Pages[0];
    TextField firstName = templateDoc.Fields["FirstName"] as TextField;
    TextField lastName = templateDoc.Fields["LastName"] as TextField;

    //make sure all widgets on this page will be flattened
    foreach (Widget widget in templatePage.Widgets)
        widget.Persistency = WidgetPersistency.Flatten;

    // create the result document
    Document outputDocument = new Document();

    for (int i = 0; i < names.Length; i += 2)
        //set the field info in the template page.
        firstName.Value = names[i];
        lastName.Value = names[i + 1];

        //append the cloned page to the output.

    //write result to disk.
    using (FileStream outFile = new FileStream(@"..\..\appendTemplate.pdf", FileMode.Create, FileAccess.Write))
Dim names As String() = {"Robert", "Stam", "Frank", "Rem", "Marnix", "van Valen", _
	"Marco", "Kesseler"}

'open the template document
Using templateStream As New FileStream("..\..\template.pdf", FileMode.Open, FileAccess.Read, FileShare.Read)
	Dim templateDoc As New Document(templateStream)

	Dim templatePage As Page = templateDoc.Pages(0)
	Dim firstName As TextField = TryCast(templateDoc.Fields("FirstName"), TextField)
	Dim lastName As TextField = TryCast(templateDoc.Fields("LastName"), TextField)

	'make sure all widgets on this page will be flattened
	For Each widget As Widget In templatePage.Widgets
		widget.Persistency = WidgetPersistency.Flatten

	' create the result document
	Dim outputDocument As New Document()

	For i As Integer = 0 To names.Length - 1 Step 2
		'set the field info in the template page.
		firstName.Value = names(i)
		lastName.Value = names(i + 1)

		'append the cloned page to the output.

	'write result to disk.
	Using outFile As New FileStream("..\..\appendTemplate.pdf", FileMode.Create, FileAccess.Write)
	End Using
End Using