.NET Core PdfPage Save As Image Using Streams Fails

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

    • Post Options:
    • Link

    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();
                        pdfPage.SaveAsPng(s);
    
                        Byte[] pageBytes = new byte[s.Length];
                        s.Read(pageBytes, 0, (int)s.Length);
                        s.Dispose();
    
                        // 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() it saves the image to disk exactly as it should.

    When using the PdfPage.SaveAsPng() overload it seems the image is corrupt and I can never render it.

  • Posted 8 March 2020, 10:35 pm EST

    Solved…

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

    
    foreach (var pdfPage in pdfDocument.Pages)
    {
    	MemoryStream s = new MemoryStream();
            pdfPage.SaveAsPng(s);
    
    	// This was the new approach that loaded the array correctly
            Byte[] pageBytes = s.ToArray();
    	s.Dispose();
    }
    
    
Need extra support?

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

Learn More

Forum Channels