2011-01-05 119 views
0

我試圖用this tutorial作爲基準來做,但它在下面指定的行中引用了空引用異常。我應該以不同的方式做這件事嗎?如果不是,爲什麼它會拋出空引用異常(pagecb都不爲空)。代碼:如何使用iTextSharp連接兩個PDF?

 string filePath = @"c:\temp\test_new.pdf"; 
     string attachPath = @"c:\temp\test.pdf"; 

     Console.WriteLine("Begin!"); 
     Document d = new Document(); 

     if(File.Exists(filePath)){File.Delete(filePath);} 

     FileStream fs = new FileStream(filePath, FileMode.Create); 

     PdfWriter pw = PdfWriter.GetInstance(d, fs); 
     d.Open(); 
     d.Add(new Paragraph("New document! Now lets add an attachment!")); 

     PdfReader pRdr = new PdfReader(new FileStream(attachPath,FileMode.Open)); 
     PdfReaderContentParser parser = new PdfReaderContentParser(pRdr); 

     MemoryStream ms = new MemoryStream(); 
     PdfWriter writer = PdfWriter.GetInstance(d, ms); 
     writer.Open(); 
     PdfContentByte cb = writer.DirectContent; 
     PdfImportedPage page; 
     int rotation; 
     d.SetPageSize(PageSize.LETTER); 
     for (int i = 1; i <= pRdr.NumberOfPages; i++) 
     { 
      d.NewPage(); 
      page = writer.GetImportedPage(pRdr, i); 
      rotation = pRdr.GetPageRotation(i); 
      if (rotation == 90 || rotation == 270) 
      { 
       cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, pRdr.GetPageSizeWithRotation(i).Height); 
      } 
      else 
      { 
    /*NULL EXCEPTION HERE!!!*/cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0); //NULL EXCEPTION HERE!!! 

      } 
     } 
+0

你確定在你的情況'頁面'或甚至'pRdr'不是null當你有異常? – Bolu 2011-01-05 17:40:44

+0

如果'pRdr'爲空,那麼會出錯7行以上不是嗎? 'page'和'cb'都不爲空。 – 2011-01-05 17:44:59

+0

我相信你可以合併2個文件,比這更少的行...我希望我的谷歌fu不會讓我失敗 – 2011-01-05 18:35:38

回答

1

1)使用PdfCopy not PdfWriter。 PdfWriter用於從文檔編寫生成的PDF。 PdfCopy是用於複製從A到B頁面。

2)如果你的問題是異常的結果請發佈異常。它會消除你在評論中看到的大部分猜測。

3)PdfImportedPage就是那個頁面的內容和資源。你失去了註釋(表單域等),書籤等等。 PdfCopy可以幫助一些,但不是全部。

+0

異常:「未將對象引用設置爲對象的實例。」這與我在OP中提到的「空引用異常」有什麼不同?此外,我正在撰寫一些PDF格式的內容,然後我想將現有的PDF複製到其中,但不確定這是否有所作爲。我會研究使用PdfCopy,敬請期待。 – 2011-01-06 22:33:01

+0

你有堆棧跟蹤嗎? – 2011-01-07 19:00:40

0

OK。我可能會抨擊不回答你的問題,但還有一個更簡單的合併兩個PDF文件的方式:不使用iTextSharp的,使用iTextDotNet

我發現瞭如何做到這一點後:http://alex.buayacorp.com/merge-pdf-files-with-itextdotnet-and-net.html

我記得這是因爲幾年前我不得不這樣做。它確實有效,而且很好。

+0

也靈活的方式:http://alex.buayacorp.com/merge-pdf-files-with -itext-and-net.html – HABJAN 2011-01-05 19:41:02