I'm trying to import pages one by one from a 2-page pdf, fill them up with pre-defined data and then finally save pdf to the disk after form flattening. However, I'm not sure about the usage of PdfStamper in here. Could anyone please help ? P开发者_开发百科lease see the sample code below. Here I'm not sure about lines in bold (between **s).
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
**var ms = new MemoryStream();
PdfReader pr = new PdfReader(page.ToPdf(writer).ToArray());
var stamper = new PdfStamper(pr, ms);
stamper.AcroFields.SetField("payrollNo", "666666");
stamper.Close();**
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
Thanks ahead !
This will solve your problem:
static PdfReader GetPdf(string filename, bool FillForm)
{
PdfReader reader2 = new PdfReader(filename);
using (MemoryStream ms = new MemoryStream())
{
var stamper = new PdfStamper(reader2, ms);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
if (FillForm)
foreach (string fieldKey in fieldKeys)
form.SetField(fieldKey, "REPLACED!");
stamper.Writer.CloseStream = false;
stamper.FormFlattening = true;
stamper.Close();
reader2.Close();
return new PdfReader(ms.ToArray());
}
}
精彩评论