在很多时候需要预先创建一个带多个字段PDF模板,然后客户可以在这些字段下填充数据,PDFKit.NET可以帮助客户在已有的PDF模板文件里填充数据,当然这些数据可以是从数据读取,也可以是手动填充,下面的事例主要介绍如何从数据库读取出数据并填充到PDF模板里的字段里,具体代码如下:
1 string[] names = { "Robert", "Stam",
2 "Frank", "Rem",
3 "Marnix", "van Valen",
4 "Marco", "Kesseler" };
5
6 //open the template document
7 using (FileStream templateStream = new FileStream(@"..\..\template.pdf", FileMode.Open, FileAccess.Read,
FileShare.Read))
8 {
9 Document templateDoc = new Document(templateStream);
10
11 Page templatePage = templateDoc.Pages[0];
12 TextField firstName = templateDoc.Fields["FirstName"] as TextField;
13 TextField lastName = templateDoc.Fields["LastName"] as TextField;
14
15 //make sure all widgets on this page will be flattened
16 foreach (Widget widget in templatePage.Widgets)
17 {
18 widget.Persistency = WidgetPersistency.Flatten;
19 }
20
21 // create the result document
22 Document outputDocument = new Document();
23
24 for (int i = 0; i < names.Length; i += 2)
25 {
26 //set the field info in the template page.
27 firstName.Value = names[i];
28 lastName.Value = names[i + 1];
29
30 //append the cloned page to the output.
31 outputDocument.Pages.Add(templatePage.Clone());
32 }
33
34 //write result to disk.
35 using (FileStream outFile = new FileStream(@"..\..\appendTemplate.pdf", FileMode.Create, FileAccess.Write))
36 {
37 outputDocument.Write(outFile);
38 }
39 }