本文介绍了使用iTextSharp的PdfStamper填充特定的导入页面并附加到新的Pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从2页的pdf中逐个导入页面,用预定义的数据填充它们,然后在表格展平后最后将pdf保存到磁盘。但是,我不确定PdfStamper的用法。有人可以帮忙吗?请参阅下面的示例代码。这里我不确定粗体的行(**之间)。
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 ? Please 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);
}
}
非常感谢!
推荐答案
这将解决您的问题:
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());
}
}
这篇关于使用iTextSharp的PdfStamper填充特定的导入页面并附加到新的Pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!