iTextSharp/C# - Fill Form Fields - Output to Browser

161 views
Skip to first unread message

Sean

unread,
Aug 9, 2007, 8:18:43 PM8/9/07
to iTextSharp
I'm trying to use iTextSharp to open a PDF, fill in a bunch of form
fields, and then stream that output to the browser (to avoid creating
extraneous PDFs on my webserver). I'm running in to a problem where
it appears that the output stream fills up and corrupts the PDF that
is output. If I uncomment one more fields.SetField it fails. Any
ideas? Here's the code:

private void fillForm()
{
string formFile = @"C:\FY08-Appendix 1.pdf";
PdfReader reader = new PdfReader(formFile);
MemoryStream stream = new MemoryStream();
PdfStamper stamp = new PdfStamper(reader, stream);
AcroFields fields = stamp.AcroFields;
// set form fields
fields.SetField("ship", ship);
fields.SetField("contract", contract);
fields.SetField("datetime", datetime);
fields.SetField("location", location);
fields.SetField("workitem", workitem);
fields.SetField("paranum", paranum);
fields.SetField("i", i);
fields.SetField("v", v);
fields.SetField("g", g);
fields.SetField("product", product);
fields.SetField("document", document);
fields.SetField("fy", fy);
fields.SetField("table", table);
fields.SetField("line", line);
fields.SetField("column", column);
fields.SetField("rh", rh);
fields.SetField("mintemp", mintemp);
fields.SetField("maxtemp", maxtemp);

// Reading 1
// fields.SetField("date1", date1);
// fields.SetField("time1", time1);
// fields.SetField("activity1", activity1);
// fields.SetField("location1", location1);
// fields.SetField("surf1", temp1);
// fields.SetField("dew1", dp1);
// fields.SetField("rh1", rh1);
// fields.SetField("dry1", dry1);
// fields.SetField("wet1", wet1);
// fields.SetField("num1", serial1);
// fields.SetField("cal1", caldue1);
// fields.SetField("sat1", sat1);
// fields.SetField("unsat1", unsat1);
// fields.SetField("cprint1", cprint1);
// fields.SetField("gprint1", gprint1);
// fields.SetField("csign1", csign1);
// fields.SetField("gsign1", gsign1);
// fields.SetField("comments1", comments1);

// flatten form fields and close document
stamp.FormFlattening = true;
// very important to keep the MemoryStream intact
stamp.Writer.CloseStream = false;
stamp.Close();

// First, convert the memorystream into an array of bytes
byte[] byteArray = stream.ToArray();

// Second, clear all content buffered in the Response
Response.Clear();

// Third, add the necessary headers
Response.AddHeader("Content-Disposition", "attachment;
filename=FY08-Appendix1.pdf");
Response.AddHeader("Content-Length",
byteArray.Length.ToString());

// Fourth, set the MIME type
Response.ContentType = "application/pdf";

// Finally, send the PDF data to the user's browser
Response.BinaryWrite(byteArray);
}

Reply all
Reply to author
Forward
0 new messages