I have a W9 PDF document that I am filling with data for just a single record per button click. Now the client would like to create a single document where each record is a page in the document. Below is our code to create a PDF for each employee.
protected void lnkFillFields_Click(object sender, EventArgs e)
{
using (Library.Data.PDFData data = new Library.Data.PDFData())
{
try
{
Document document = new Document();
PdfCopy writer = new PdfCopy(document, Response.OutputStream);
document.Open();
foreach (EmployeeData emp in data.sp_select_employee_data())
{
//Creates a PDF from a byte array
PdfReader reader =
new PdfReader((Byte[])data.sp_select_doc(16).Tables[0].Rows[0]["doc"]);
//Creates a "stamper" object used to populate interactive fields
MemoryStream ms = new MemoryStream();
PdfStamper stamper = new PdfStamper(reader, ms);
try
{
//MUST HAVE HERE BEFORE STREAMING!!!
//This line populates the interactive fields with your data.
// false = Keeps the fields as editable
// true = Turns all of the editable fields to their read-only equivalent
stamper.FormFlattening = false;
//fill in PDF here
stamper.Close();
reader.Close();
MergePDFs(writer, ms);
}
catch (Exception ex)
{
throw ex;
}
}
document.Close();
//Stream the file to the user
Response.ContentType = "application/pdf";
Response.BufferOutput = true;
Response.AppendHeader("Content-Disposition", "attachment; filename=W9"+ "_Complete.pdf");
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
}
Inserting a page wasn't the way to go. Instead, merging the documents was essentially what we wanted. Therefore, we have come up with this method:
UPDATE Below is the method that we came up with that successfully stitches a new PDF to the previous one.
private static void MergePDFs(PdfCopy writer, MemoryStream ms)
{
PdfReader populated_reader = new PdfReader(ms.ToArray());
//Add this pdf to the combined writer
int n = populated_reader.NumberOfPages;
for (int i = 1; i <= n; i++)
{
PdfImportedPage page = writer.GetImportedPage(populated_reader, i);
writer.AddPage(page);
}
}
What we need to do is create all of this in memory, then spit it out to the user for download.