PageStamp.AlterContents() NullReferenceException
this is the problem:
i've got this piece of code...
It keeps throwing a NullReferenceException at the stamp.AlterContents(); line.
i've got no clue on what's going on. Any help appreciated!
public static byte[] concatAndAddContent(List<byte[]> pdf)
{
byte [] todos;
using(MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
doc.Open();
PdfCopy copy = new PdfCopy(doc, ms);
PdfCopyFields copy2 = new PdfCopyFields(ms);
PdfReader reader;
foreach (byte[] p in pdf)
{
开发者_如何学Go reader = new PdfReader(p);
int pages = reader.NumberOfPages;
// loop over document pages
for (int i = 1; i <= pages; i++)
{
PdfImportedPage page = copy.GetImportedPage(reader, i);
PdfCopy.PageStamp stamp = copy.CreatePageStamp(page);
PdfContentByte cb = stamp.GetUnderContent();
cb.SaveState();
stamp.AlterContents();
copy.AddPage(page);
}
}
doc.Close();
todos = ms.GetBuffer();
ms.Flush();
ms.Dispose();
}
return todos;
}
i've got iTextSharp version 5.0.4 in VisualStudio 2010
Please post your exception stack trace.
While I'm not sure what's causing the exception, I can tell you that calling cb.saveState()
without a matching cb.restoreState()
is A Bad Thing. In the Java version, this will throw an IllegalPdfSyntaxException. In C#, this may have been converted to an NPE, but that seems a bit of a stretch.
Saving and restoring the state is used when you want to do something and then "go back" later. For example
Draw some stuff
save the state
create a clipping region
draw some clipped stuff
restore the state
draw some unclipped stuff.
This sort of thing happens A LOT in PDF. Want to draw an image? You have to change the Current Transformation Matrix (CTM) to put the image where you want at the size you want. Unless you want everything that comes after to be likewise transformed (and you never do), you have to wrap the matrix change and image draw in a save/restore block. iText handles this for you when you call cb.addImage(...), but it's still happening behind the scenes.
精彩评论