Hello Jon!
The main problem in scenario we are discussing is that all data of document are stored in memory stream.
You load returnItem document from finalDoc memory stream :
public static Aspose.Pdf.Document MergeRenderDocsToPDF(Dictionary itemsToMerge)
{
...
MemoryStream finalDoc = new MemoryStream();
... //some action...
pdfEditor.Concatenate(itemLists, finalDoc);
... //some action...
returnItem = new Aspose.Pdf.Document(finalDoc);
finalDoc.Close(); // after closing memory stream document data are no more accessible
// and we can get "Stream can not be read" error.
return returnItem;
}
Please note that not all data from memory stream are loaded into document object
after creating document and loading it from stream.
Some parts of document are loaded from document data (memory stream in our case)
only when they are required i.e. when these parts were used.
The purpose of this approach is achievement of better performance and reduction of required memory.
For example if we work with a large file (for example 500Mb) we should not load all document into memory;
else we would have excess memory allocation and loss of the performance
(because we would need to allocate additional 500Mb memory and to waste time to load all document data )
That's why data of document are required even after document created by stream.
And yes, you document was loaded from file and file was deleted or damaged
(or for example removeable device where file was placed was removed)
we will get error "Stream can not be read" when we try work with the document.
You can avoid this problem if you will return Stream from your method MergeRenderDocsToPDF
instead of Document:
public static Stream MergeRenderDocsToPDF(Dictionary itemsToMerge)
{
...
MemoryStream finalDoc = new MemoryStream();
... //some action...
pdfEditor.Concatenate(itemLists, finalDoc);
... //some action...
return finalDoc; //return memory stream instead of document
//remove these lines.
//returnItem = new Aspose.Pdf.Document(finalDoc);
//finalDoc.Close();
//return returnItem;
}
and create new document from this data when you need this.
public void UseOfDocument()
{
//get data from method
Stream data = MyClass.MergeRenderDocsToPDF(itemsToMerge);
//load document from data
Document doc = new Document(data);
//make some operations with document.....
//......
//and save it for example into file
doc.Save("myfile.pdf");
//we dont need document data (and document too because it is already saved) anymore, so close it
data.Close();
}
Please note that you still need to close stream in your code since it was created in your code too.