我正在创建一个函数,使用ITextSharp在现有PDF文档的末尾添加页面。 PDF包含我在添加新页面之前填充的acrofields。
当我在不添加新页面的情况下执行它时,将按预期生成PDF,填充所有字段。 但是当我执行并调用我的函数添加页面时,PDF会生成新页面,但所有字段现在都是空白的......
这是我的代码:
// The first PdfReader in the list is my main pdf, with all fields.
private void AddPages(List<PdfReader> pdfs)
{
byte[] all;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.SetPageSize(PageSize.A4);
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
foreach (PdfReader p in pdfs)
{
int pages = p.NumberOfPages;
// loop over document pages
for (int i = 1; i <= pages; i++)
{
doc.SetPageSize(PageSize.A4);
doc.NewPage();
page = writer.GetImportedPage(p, i);
cb.AddTemplate(page, 0, 0);
}
}
doc.Close();
all = ms.GetBuffer();
ms.Flush();
ms.Dispose();
}
// I tried to add this code, but doesn't change anything.
AcroFields fields = Output.AcroFields;
// Output is my PdfStamper I returned, my final PDF
Output = new PdfStamper(new PdfReader(all), outStream);
foreach (var field in fields.Fields)
Output.AcroFields.Fields.Add(field);
}
知道为什么我的字段被清空以及如何解决它?
非常感谢
修改
根据评论,这是我的新功能:
byte[] all;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, ms);
doc.Open();
foreach (PdfReader pdf in pdfs)
copy.AddDocument(pdf);
doc.Close();
all = ms.ToArray();
}
Output = new PdfStamper(new PdfReader(all), outStream);
但我仍有同样的问题。我做错了什么?
答案 0 :(得分:0)
如果它对任何人都有帮助,这里的代码现在可用了:
byte[] all;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, ms);
copy.SetMergeFields();
doc.Open();
foreach (PdfReader pdf in pdfs)
copy.AddDocument(pdf);
doc.Close();
all = ms.ToArray();
}
Output = new PdfStamper(new PdfReader(all), outStream);
Output.AcroFields.GenerateAppearances = true;
感谢@Bruno Lowagie和@mkl!