Last active
August 29, 2015 14:04
-
-
Save bungard/de321995a418bbd0f479 to your computer and use it in GitHub Desktop.
C# to fill PDF form from a Given DataTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This is utilizing iTextSharp for the PdfReader, PdfStamper and AcroFields classes. | |
*/ | |
DataTable dt = new DataTable();/* fill the DT however you please */ | |
String pdfTemplate = "PATH_TO_PDF_FORM"; | |
System.IO.MemoryStream m = new System.IO.MemoryStream(); | |
PdfReader pdfReader = new PdfReader(pdfTemplate); | |
PdfStamper pdfStamper = new PdfStamper(pdfReader, m); | |
AcroFields testForm = pdfStamper.AcroFields; | |
foreach (DataColumn column in dt.Columns) | |
{ | |
try | |
{ | |
/*SetField does not validate the passed field exists in the form. Therefore, we can pass all fields | |
in the DataTable and those matching form field name, will be filled. | |
*/ | |
if (column.DataType.ToString() == "System.DateTime") | |
{ | |
//Arbitrariliy formatting DateTimes in this fashion | |
DateTime tmpDate = (DateTime)dt.Rows[0][column.ColumnName]; | |
testForm.SetField(column.ColumnName, tmpDate.ToShortDateString()); | |
} | |
else | |
testForm.SetField(column.ColumnName, cleanString(dt.Rows[0][column.ColumnName].ToString())); | |
} | |
catch (Exception ex) | |
{ | |
} | |
} | |
try | |
{ | |
//Explicitly set a column called "Date" to the current date | |
testForm.SetField("Date", DateTime.Today.ToShortDateString()); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("Exception in setting form fields: " + ex.Message); | |
} | |
pdfStamper.Close(); | |
pdfReader.Close(); | |
/* Now do something with the MemoryStream, as you'd like */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment