I tried to do it using this tutorial as a base, but it's throwing a null reference exception at the line specified below. Should I be doing this a different way? If not, why would it throw an null reference exception (both page
and cb
are NOT null). Code:
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!!!
}
}