2015-01-05 132 views
0

提取一個頁面的結果,我想測試從PDF文檔中的單個頁面的提取,但我發現了一個NullReferenceException每當我嘗試。中的NullReferenceException

var document = new Document(); 
var stream = new MemoryStream(); 
var writer = PdfWriter.GetInstance(document, stream); 

document.Open(); 
document.Add(new Paragraph("This is page 1.")); 
document.NewPage(); 
document.Add(new Paragraph("This is page 2.")); 
document.Close(); 

var copystream = new MemoryStream(); 
var copy = new PdfCopy(document, copystream); 
copy.Open(); 
var reader = new PdfReader(stream.ToArray()); 
var page = copy.GetImportedPage(reader, 2); 
copy.AddPage(page); 
copy.Close(); // code throws exception here 

我已經嘗試添加writer.CloseStream = false,但我還是落得同樣的NullReferenceException

Object reference not set to an instance of an object. 
    at iTextSharp.text.Document.get_Left() 
    at iTextSharp.text.pdf.PdfDocument.SetNewPageSizeAndMargins() 
    at iTextSharp.text.pdf.PdfDocument.NewPage() 
    at iTextSharp.text.pdf.PdfDocument.Close() 
    at iTextSharp.text.pdf.PdfCopy.Close() 
    at iTextTest.Controllers.HomeController.Index() in line 41 
+0

剛剛添加,我的不好。的 –

+0

可能重複[什麼是一個NullReferenceException,如何解決呢?(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Servy

+1

那麼這似乎是iTextSharp中的一個錯誤。他們可能希望在那裏添加空處理並拋出適當的異常,如「無邊距設置」或任何根本原因。 [瀏覽來源:'Left'屬性不'返回pageSize.GetLeft(marginLeft);'](http://sourceforge.net/p/itextsharp/code/HEAD/tree/trunk/src/core/iTextSharp/text /Document.cs),其中'pageSize'大概是'null'。 – CodeCaster

回答

1

請改變你這樣的代碼:

var document = new Document(); 
var stream = new MemoryStream(); 
var writer = PdfWriter.GetInstance(document, stream); 

document.Open(); 
document.Add(new Paragraph("This is page 1.")); 
document.NewPage(); 
document.Add(new Paragraph("This is page 2.")); 
document.Close(); 

document = new Document(); // this is the line you need to add 
var copystream = new MemoryStream(); 
var copy = new PdfCopy(document, copystream); 
copy.Open(); 
var reader = new PdfReader(stream.ToArray()); 
var page = copy.GetImportedPage(reader, 2); 
copy.AddPage(page); 
copy.Close(); // code throws exception here 

你重用你來從頭開始創建一個新文檔document對象。該document實例已關閉。如果在PdfCopy的上下文中使用document,則需要新的Document實例。

0

我已經審查了PdfDocument源作爲可以在這裏找到:http://sourceforge.net/p/itextsharp/code/HEAD/tree/trunk/src/core/iTextSharp/text/pdf/PdfDocument.cs#l2334

PdfDocument在方法SetNewPageSizeAndMargins開始時將專用字段nextPageSize的值分配給字段pageSize。要停止nextPageSizenull(並因此導致您的pageSize被設置爲null,並觸發NullReferenceException當它在下一次訪問)關閉副本之前呼籲文檔SetPageSize

保持默認頁面大小,請撥打SetPageSize如下:

document.SetPageSize(document.PageSize); 

這很可能是由PdfDocument類,我懷疑開發商的監督,就是要設定nextPageSize默認值並不是。

+0

我在'copy.AddPage(page)'後面放了'copy.SetPageSize(document.PageSize)',但我仍然在'copy.Close()'上得到相同的異常。 –

+0

我的錯誤。請把它放在文件上。這是拷貝關閉文檔引發異常的文檔。更新了我的答案。 –

+0

我在'document.Close()'之前添加了'document.SetPageSize(document.PageSize)',但我仍然得到拋出的異常。我瀏覽了源代碼,看起來問題的確在'nextPageSize'中,因爲它仍然是'null'。 –