2011-05-10 51 views
2

我成功地使用iTextSharp以PDF形式讀取表單,填寫表單中的字段,並將其寫回客戶端。我現在已經得到了一些要求,如果某些頁面全部是空白的,就應該刪除它(爲了這個問題的目的,我可以檢查一個布爾變量來知道我是否需要刪除這些頁面,我的理解是這樣做在iTextSharp中,您實際上是將PDF從一個複製到另一個,並且省略了要刪除的頁面。使用iTextSharp複製PDF表單

我有這個工作,但是我在複製的PDF上丟失了表單;即沒有寫出值在嘗試複製PDF以「刪除」某些頁面之前,值正在被正確寫入。

如何保留我在複製表單時已創建的PDF表單或者是否有更好的刪除方法到目前爲止,這是我的代碼,它將PDF寫入一個文件,但不填寫表單(大概是因爲澳洲英語複製時不保留形式):

string file = "output.pdf"; 
    PdfReader reader = new PdfReader("template.pdf"); 

    Document doc = new Document(); 
    using (MemoryStream ms = new MemoryStream()) 
    { 

     PdfWriter writer = PdfWriter.GetInstance(doc, ms); 
     doc.Open(); 
     doc.AddDocListener(writer); 
     for (int i = 1; i <= reader.NumberOfPages; i++) 
     { 
      bool skipPage = this.SkipPage; // some nifty logic here 
      if (skipPage) 
       continue; 

      doc.SetPageSize(reader.GetPageSize(i)); 
      doc.NewPage(); 
      PdfContentByte cb = writer.DirectContent; 
      PdfImportedPage page = writer.GetImportedPage(reader, i); 
      int rotation = reader.GetPageRotation(i); 
      if (rotation == 90 || rotation == 270) 
       cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height); 
      else 
       cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0); 
     } 
     reader.Close(); 
     doc.Close(); 
     using (FileStream fs = new FileStream(file, FileMode.Create)) 
     { 
      // this is the part stumping me; I need to use a PdfStamper to write 
      // out some values to fields on the form AFTER the pages are removed. 
      // This works, but there doesn't seem to be a form on the copied page... 
      this.stamper = new PdfStamper(new PdfReader(ms.ToArray()), fs); 
      // write out fields here... 
      stamper.FormFlattening = true; 
      stamper.SetFullCompression(); 
      stamper.Close(); 
     } 
    } 

回答

1

沒關係,我似乎已經能夠通過使用SelectPages方法上的PDF閱讀器來弄明白,我能避免做一個實際的複製的文件。

+0

打我吧... +1 – 2011-05-10 19:34:22

+3

爲什麼不發佈正確的代碼示例而不是提示。 – 2013-08-14 19:27:51

+0

是的,一個正確的代碼示例將是一件好事! – CodeIt 2017-03-23 17:33:59