MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to write a .SVG to pdf with PdfSharp

I'm using PdfSharp and saving .png files. It works fine. Now I need to save SVG images and I'm getting an error

System.OutOfMemoryException: Out of memory.

The code is

var path = @"D:\Projects\ProjectName\Content\Images\Instruments";
path += Path.GetFileName(instrument.Src); //instrument.src is a valid name and the path is a valid path on the local machine, which is where I'm testing

if (!File.Exists(path))
    return;  //never hit as the path is correct

var img = XImage.FromFile(path); //out of memory
//more code

If I change the above from .svg to .png it works fine (since I have both, a .png and .svg file with the same name)

How can I save the SVG image to PDF using PDF Sharp?

Upvotes: 3

Views: 6257

Answers (2)

PDFsharp supports raster images like PNG and JPEG. Vector images like SVG are not yet supported. This is not a bug, this is an implementation restriction. Pages from PDF files can be used like images and allow using vector images with PDFsharp.

XImage.FromFile passes the image to either GDI+ or WPF (depending on the build you are using) and expects to get a raster image in return. I do not know what GDI+ or WPF return for SVG images.

If you find source code that draws SVG images using a Graphics object then you can easily adopt that for PDFsharp's XGraphics object.

Or try to find a library that converts SVG to raster images or PDF files.

Upvotes: 8

KM Koeln
KM Koeln

Reputation: 9

You can do it as follows:

  • Step 1: open your vector image in Inkscape
  • Step 2: save the image in Inkscape as pdf file
  • Step 3: import this new pdf file in your pdf document like this:
using (var doc = new PdfSharp.Pdf.PdfDocument())
{
    var page = doc.AddPage();
    using (var gr = PdfSharp.Drawing.XGraphics.FromPdfPage(page, PdfSharp.Drawing.XGraphicsPdfPageOptions.Append))
    {
        using (var imgForm = PdfSharp.Drawing.XPdfForm.FromFile("fileWithVectorImage.pdf"))
        {
            gr.DrawImage(imgForm, new PdfSharp.Drawing.XPoint(10, 10));
        }

        //other pdf stuff with gr.DrawString etc.
    }
    doc.Save("resultPdfFile.pdf");
}

Upvotes: -1

Related Questions