Home > Back-end >  Error converting image stream to PDF on server using PDFsharp
Error converting image stream to PDF on server using PDFsharp

Time:10-22

I'm trying to include an image from a SQL database into a PDF file with the following code:
(Using PDFsharp version 1.50.5147)

Code:

private PdfDocument openImageFromByteArray(byte[] ImageStream)
{
    MemoryStream stream = new MemoryStream(ImageStream);
    PdfDocument OutputDocument = new PdfDocument();
    OutputDocument.Pages.Add(new PdfPage());

    XGraphics xgr = XGraphics.FromPdfPage(OutputDocument.Pages[0]);
    XImage img = XImage.FromStream(stream);
    xgr.DrawImage(img, 0, 0);

    //OutputDocument.Save("C:\\Test\\Test.pdf");
    //OutputDocument = PdfReader.Open("C:\\Test\\Test.pdf", PdfDocumentOpenMode.Import);
    //System.IO.File.Delete("C:\\Test\\Test.pdf");

    return OutputDocument;
}

If I save OutputDocument locally and then reload the saved PDF it works fine (the commented out part), but as soon as the code runs without the commented out part, or from the server I need to deploy to, I get the error that the image was not decoded properly. I can't save or create files on the server due to permissions.

Here is the error on the PDF from the server:

An error occurred while processing the file test.png The reader could not process this file because it either used non - supported features from a different version of Adobe Acrobat or because the file has been damaged, for example it was sent as an email attachment and wasn't correctly decoded. You may be able to download and print the document manually to include in your report or print it from your backup copy.

I've tried a number of different code changes, but they either come out the same, or I have actual code errors so I cannot even build the project.

CodePudding user response:

If the error happens only when you comment that part I assume it happens outside this method. My guess is that the OutputDocument.Save (commented) ends up closing the MemoryStream, something you do not do otherwise.

Try putting an using statement when you create the MemoryStream (check bellow) and check if it works, or edit your question to include the place code where the error occurs.

private PdfDocument openImageFromByteArray(byte[] ImageStream)
{
  using(MemoryStream stream = new MemoryStream(ImageStream))
  {
    PdfDocument OutputDocument = new PdfDocument();
    (...)
    return OutputDocument;
  }
}

CodePudding user response:

The method shown in the code returns a PdfDocument object, but the MemoryStream used to create the XImage is disposed before creating the PDF file (in code not shown here).

I assume it would work if you would create the PDF in the routine and return the PDF instead of the PdfDocument.

The .Save(...) that is now commented out accesses the MemoryStream before it gets disposed and thus has no problem.

  • Related