I've adapted this code from the ItextSharp version to Itext 8.0.5
public MemoryStream GenerateReportPdf(ReportData reportData)
{
using (MemoryStream ms = new MemoryStream())
{
var pdfDoc = new PdfDocument(new PdfWriter(ms));
var doc = new Document(pdfDoc);
styles = GetStyles();
AddReportContent(doc, reportData);
doc.Close();
return ms;
}
}
The doc builds correctly, and in debug I can see the Memorystream is approximately correct.
In the iTextSharp version, doc.close() does not dispose of the MemoryStream, and we're able to return it to the function that will save the file to AWS. In this version, the MemoryStream is disposed and I'm unable to access it.
I tried writing to a byte array, then recreating a memorystream and passing it along. That saved a file, but it was not recognized as a PDF.
Any clues or ideas as to how to proceed would be welcome.
Tried: Returning ms, expected ms object passed to calling method, got disposed ms.
Tried: Returing recreate ms with ByteArray before doc.close, expected ms object passed to calling method, got memorystream that was not valid pdf file.
Tried: doc.flush() before doc.Close(), expected ms object passed to calling method, got disposed ms.
Edit:
I appreciate your comments. To address the duplicate the issue is Not primarily with the using statement. I went down the 'using' path because that's what the tutorials said. I want to return the ms to my calling method, which will then pass it to my recorder/uploader methods in a different object. The AWS uploader is expecting a stream of some sort.
I have now removed the 'using', and the code is as follows:
public MemoryStream GenerateReportPdf(ReportData rptData)
{
MemoryStream ms = new MemoryStream();
var pdfDoc = new PdfDocument(new PdfWriter(ms));
var doc = new Document(pdfDoc);
styles = GetStyles();
AddReportContent(doc, rptData);
doc.Close();
return ms;
}
The returned Memorystream ms is still disposed.
Try the following:
public MemoryStream GenerateReportPdf(ReportData rptData)
{
var ms = new MemoryStream();
var writer = new PdfWriter(ms);
// writer.SetCloseStream(false);
var pdfDoc = new PdfDocument(writer);
// pdfDoc.SetCloseWriter(false);
var doc = new Document(pdfDoc);
styles = GetStyles(); // not sure if you need this line
AddReportContent(doc, rptData);
doc.Close();
ms.Position = 0;
return ms;
}
SetCloseWriter
or SetCloseStream
will ensure that closing the document doesn't close the stream. I can't remember which of the two it is - try both of the commented out lines, I believe one will work.
There is no need for a using
block for MemoryStream
since it doesn't do much useful (i.e. it doesn't actually release the underlying array). Plus, you don't want to dispose it anyway given you want it consumed by the calling code.