Bookmark and Share

itextsharp memorystreaming

I ran into an issue with MemoryStream writing when building pdfs with itextsharp. MemoryStream allocates blocks of bytes. It gives you all the blocks back when you call GetBuffer, so if you write out a file with the full buffer you'll find a bunch of hex 0's at the end of the file that should not be there.

This is fine for Adobe viewer, it handles it properly, but some import programs / pdf parsers fail very badly when there are extra 0 bytes at the end of the file.

If you thought you could check the length of the memorystream before the stream is closed by itextsharp, you are incorrect. itextsharp adds a bunch of bytes to the pdf when you call close, so you need to check the length after Close() was called on the PdfWriter.

Below you'll find the way to get around the issue. Set CloseStream to false on the PdfWriter, check the length of the stream after Close() and return the correct amount of bytes.

		PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, pdfDocument);
		writer.CloseStream = false;
		writer.SetEncryption(true, null, "Protected89OPasswordByASHR", PdfWriter.AllowScreenReaders | PdfWriter.ALLOW_PRINTING);

		long length = pdfDocument.Length;
		byte[] fullBuffer = pdfDocument.GetBuffer();

		//25 25 45 4f 46 0a == %%EOF.
		//List eofMarks = new List(6);
		byte[] returnArray = new byte[length];

		for(int i = 0;i < length;i++)
			returnArray[i] = fullBuffer[i];

		return returnArray;