I want to save a PDFSharp.Pdf.PDFDocument by it's Save method to a Stream, but it doesn't attach the pdf header settings to it. So when I read back the Stream and return it to the user, he see that the pdf file is invalid. Is there a solution to attach the pdf header settings when PdfSharp saves to memory?
So the solution:
MigraDoc.DocumentObjectModel.Document doc = new MigraDoc.DocumentObjectModel.Document();
MigraDoc.Rendering.DocumentRenderer renderer = new DocumentRenderer(doc);
MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer();
pdfRenderer.PdfDocument = pDoc;
pdfRenderer.DocumentRenderer = renderer;
using (MemoryStream ms = new MemoryStream())
{
pdfRenderer.Save(ms, false);
byte[] buffer = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Flush();
ms.Read(buffer, 0, (int)ms.Length);
}
There is this MigraDoc stuff which comes with PdfSharp, but i hardly found any proper doc/faq for it. After hours of googling i've found a snippet which was something like this. Now it works.
If you think there is an issue with PdfDocument.Save, then please report this on the PDFsharp forum (but please be more specific with your error description). Your "solution" looks like a hack to me. "pdfRenderer.Save" calls "PdfDocument.Save" internally. Whatever the problem is - your "solution" still calls the same Save routine.
Edit: To get a byte[] containing a PDF file, you only have to call:
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
byte[] bytes = stream.ToArray();
Early versions of PDFsharp do not reset the stream position.
So you have to call
ms.Seek(0, SeekOrigin.Begin);
to reset the stream position before reading from the stream; this is no longer required for current versions.
Using ToArray can often be used instead of reading from the stream.
The best place to ask PDFsharp and MigraDoc Foundation related questions is the PDFsharp forum. The PDFsharp Team will not monitor stackoverflow.com on a regular basis.
PDFsharp Forum:
http://forum.pdfsharp.net/