我一直试图抓住iText7 c#,运气不佳。
我的目标是:
我有不同的部分工作,但我不能让它一起工作
var memoryStream = new MemoryStream();
PdfReader reader = new PdfReader("untitled-1.pdf"); //Iput
PdfWriter writer = new PdfWriter(memoryStream); //output
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
var fields = form.GetFormFields();
if(fields.ContainsKey("address")) {
fields["address"].SetValue("first\nlast");
}
form.FlattenFields();
pdfDoc.Close();
byte[] b = memoryStream.ToArray();
File.WriteAllBytes(@"t.pdf", b);
克隆页面:
// create clone page x times
PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf").SetSmartMode(true));
pdfDoc.InitializeOutlines();
PdfDocument srcDoc;
for (int i = 0; i<5; i++) {
srcDoc = new PdfDocument(new PdfReader("untitled-1.pdf"));
// copy content to the resulting PDF
srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdfDoc);
}
pdfDoc.Close();
答案 0 :(得分:0)
创建一个pdf文件,其中包含一个名为address的表单和文本字段作为模板,另存为untitled1-pdf。
此代码将创建一个空文档,然后为用户中的每个用户加载并填写用户的字段地址。
然后将填好的表格展平并复制到新文档中。 完成所有操作后,文档将保存为result.pdf
// B
static void Main(string[] args)
{
List<string> users = new List<string> { "Peter", "john", "Carl" };
byte[] result = createPdf(users, "untitled-1.pdf");
File.WriteAllBytes(@"result.pdf", result);
}
public static byte[] createPdf(List<string> users,string templateFile)
{
// create clone page for each user in users
using (MemoryStream memoryStream = new MemoryStream())
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(memoryStream).SetSmartMode(true));
pdfDoc.InitializeOutlines();
PdfDocument srcDoc;
foreach (var u in users)
{
MemoryStream m = new MemoryStream(fillForm(u,templateFile));
srcDoc = new PdfDocument(new PdfReader(m));
// copy content to the resulting PDF
srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdfDoc);
}
pdfDoc.Close();
return memoryStream.ToArray();
}
}
public static byte[] fillForm(string user,string templateFile)
{
using (var memoryStream = new MemoryStream())
{
PdfReader reader = new PdfReader(templateFile); //Iput
PdfWriter writer = new PdfWriter(memoryStream); //output
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
var fields = form.GetFormFields();
if (fields.ContainsKey("address"))
{
fields["address"].SetValue(user);
}
form.FlattenFields();
pdfDoc.Close();
byte[] b = memoryStream.ToArray();
return b;
}
}