提取页面会导致NullReferenceException

时间:2015-01-05 15:26:57

标签: c# itextsharp nullreferenceexception

我正在尝试从PDF文档中测试单个页面的提取,但每当我尝试时,我都会得到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

2 个答案:

答案 0 :(得分: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实例已经关闭。在document的上下文中使用PdfCopy时,您需要一个新的Document实例。

答案 1 :(得分:0)

我已经查看了PdfDocument的来源,可以在这里找到:http://sourceforge.net/p/itextsharp/code/HEAD/tree/trunk/src/core/iTextSharp/text/pdf/PdfDocument.cs#l2334

PdfDocument在方法nextPageSize的开头将字段pageSize的值分配给字段SetNewPageSizeAndMargins。要阻止nextPageSize成为null(从而导致pageSize设置为空,并在下次访问时触发NullReferenceException,请在SetPageSize上调用SetPageSize关闭副本之前的文件。

要保留默认页面大小,请按以下方式调用document.SetPageSize(document.PageSize);

{{1}}

这很可能是PdfDocument类开发人员的疏忽,我怀疑这是为nextPageSize设置默认值而不是。