.NET Core PdfPage Save As Image Using Streams Fails

Posted by: andy.baker on 6 March 2020, 8:20 am EST

  • Posted 6 March 2020, 8:20 am EST

    I have a Web API that accepts uploaded files where I need to rasterize each page. I need to keep the images as byte arrays as I cannot write these files to disk (if I could this wouldn't be an issue). I've tried the different image types Bmp, Jpeg, etc... without success.

    foreach (var pdfPage in pdfDocument.Pages)
    Stream s = new MemoryStream();

    Byte[] pageBytes = new byte[s.Length];
    s.Read(pageBytes, 0, (int)s.Length);

    // This fails
    System.IO.File.WriteAllBytes("C:\\TEMP\\BadPage " + (pdfPage.Index + 1).ToString() + ".png", pageBytes);

    // This works
    pdfPage.SaveAsPng("C:\\TEMP\\GoodPage " + (pdfPage.Index + 1).ToString() + ".png");

    When using the PdfPage.SaveAsPng(<file path>) it saves the image to disk exactly as it should.

    When using the PdfPage.SaveAsPng(<stream>) overload it seems the image is corrupt and I can never render it.
  • Marked as Answer

    Replied 8 March 2020, 10:35 pm EST


    Required a slightly different approach to the code, but here is what worked.

    foreach (var pdfPage in pdfDocument.Pages)
    MemoryStream s = new MemoryStream();

    // This was the new approach that loaded the array correctly
    Byte[] pageBytes = s.ToArray();
Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels