Search code examples
c#asp.net.netpdfsharp.net-4.6

Load image without using system.drawing.image


I would like to load a image-stream so that it can be converted to a pdf using PDFsharp.

The following code is working in my test/console-application, but not in my project running with ASP.NET Framework 4.6.1. This is because I am using System.Drawing.Image.

Classes within the System.Drawing.Imaging namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions.

Source: Microsoft

How can we solve this problem? My preference is to have everything in memory.

My working code in the console application:

PdfDocument pdfDoc = new PdfDocument();
pdfDoc.Pages.Add(new PdfPage());
MemoryStream MemStream = new MemoryStream(inputStream); // Inputstream as byte[]

Image imgSource = Image.FromStream(MemStream); // This will fail
XImage imgX = XImage.FromGdiPlusImage(imgSource);

XGraphics xgr = XGraphics.FromPdfPage(pdfDoc.Pages[0]);
xgr.DrawImage(imgX, 0, 0);

MemoryStream outputStream = new MemoryStream();
pdfDoc.Save(outputStream, false);
byte[] dataConverted = outputStream.ToArray();
pdfDoc.Close();

return dataConverted;

Solution

  • Just pass the stream to PDFsharp:

    public static XImage FromStream(Stream stream)
    

    With PDFsharp 1.50 this method is public. I think it was not public with version 1.3x.

    Use the WPF build of PDFsharp - the GDI build uses Image.FromStream internally.