在ITextSharp中合并来自相同表单的PDF字段

时间:2012-12-11 11:36:22

标签: c# pdf itextsharp

我有两个PDF表单 - 一个orignial表单和一个新表单。新表单上有x额外的acro fields,但它没有原始PDF字段。

我想将旧PDF中的字段合并到新的PDF表单中。新的字段/字段会移动旧字段的一些占位符,因此它们可能重叠或不在正确的位置,但这是无关紧要的。

我尝试了什么

//Get the old PDF
PdfReader oldPdfReader = new PdfReader("Old.Pdf");
MemoryStream oldMs = new MemoryStream();
PdfStamper oldPdfStamper = new PdfStamper(oldPdfReader, oldMs);
//Get the new PDF
PdfReader newPdfReader = new PdfReader("New.Pdf");
MemoryStream newMs = new MemoryStream();
PdfStamper newPdfStamper = new PdfStamper(newPdfReader, newMs);

foreach(var oldField in oldPdfStamper.AcroFields.Fields)
{
   //Do a check to see if the field isn't already added
   if(!newPdfStamper.AcroFields.Fields.Any(x => x.Key == oldField.Key))
      newPdfStamper.AcroFields.Fields.Add(oldField);
}

即使调试到达add,这也仅输出新字段,我得出结论这是不正确的,我需要在某些方面绘制字段。

我也尝试过以下示例:

Merging multiple PDFs using iTextSharp in c#.net

它会从New.PDF开始新字段,但不会从Old.PDF继承字段。关于如何从两个PDF表单合并AcroFields的任何想法?

1 个答案:

答案 0 :(得分:0)

  //Get the old PDF
  PdfReader oldPdfReader = new PdfReader(@"old.pdf");
  MemoryStream oldMs = new MemoryStream();
  PdfStamper oldPdfStamper = new PdfStamper(oldPdfReader, oldMs);
  //Get the new PDF
  PdfReader newPdfReader = new PdfReader(@"new.pdf");
  MemoryStream newMs = new MemoryStream();
  PdfStamper newPdfStamper = new PdfStamper(newPdfReader, newMs);
  AcroFields af = oldPdfStamper.AcroFields;

  foreach (var oldField in oldPdfStamper.AcroFields.Fields)
  {
    var rectangles = af.GetFieldPositions(oldField.Key).Select(x => x.position.GetRectangle(x.position.Top, x.position.Bottom));
    foreach (var rectangle in rectangles)
    {
      TextField tf = new TextField(newPdfStamper.Writer, rectangle, oldField.Key);
      newPdfStamper.AddAnnotation(tf.GetTextField(), af.GetFieldPositions(oldField.Key).First().page);
    }
  }