Search code examples
c#memorystreampdfsharp

PDF to MemoryStream and then back


I have generated a pdf using PDFSharp.

I call the save method, and save it to disk, and the file is perfect.

I then need to get the file into a MemorySteam, in preparion of sending it to my website to download. However, the file ends up invalid. corrupt.

So, to see where it's going wrong, I have put the file into a MemoryStream, and then I try write that steam to a file, to confirm all is OK. It isn't.

Here I sav the file to disk, to check it (debugging), and then put it into a stream:

            document.Save("c:\\temp\\ggg.pdf");

            MemoryStream ms = new MemoryStream();
                document.Save(ms, false);
                byte[] buffer = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Flush();
                ms.Read(buffer, 0, (int)ms.Length);
                return ms;

I then return 'ms' to my calling function, and attempt to write the stream to a file:

 var doc = GeneratePdf(1);

            using (FileStream file = new FileStream("c:\\temp\\222.pdf", FileMode.Create, System.IO.FileAccess.Write))
            {
                byte[] bytes = new byte[doc.Length];
                doc.Read(bytes, 0, (int)doc.Length);
                file.Write(bytes, 0, bytes.Length);
                doc.Close();
            }

But 222.pdf is not a valid pdf. ggg.pdf was fine. So I am doing something wrong when I write to stream, and write to disk. Why is the file getting corrupted?


Solution

  • I cannot reproduce your issue (PdfSharp 1.32.3057.0). It seems to me that you are messing too much with manual stream copying.

    Try the following code, which correctly creates a pdf, streams it into a MemoryStream and than saves it into a file:

    var pdf = new PdfSharp.Pdf.PdfDocument();
    
    var page = pdf.AddPage();
    var gfx = XGraphics.FromPdfPage(page);
    var font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
    gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
    
    var ms = new MemoryStream();
    pdf.Save(ms, false);
    ms.Position = 0;
    
    using (var file = File.OpenWrite("test.pdf"))
        ms.CopyTo(file); // no need for manual stream copy or buffers