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

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

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

What I have tried

//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)

2 years ago

//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);
    }
  }