简体   繁体   中英

How to convert SVG to PDF C#?

I've had this issue for a few days and have tried a number of things. Essentially, I'm having users edit an SVG and once they're finished, they save it back to a file path on the server. My problem is my SVG contains an href to a file in a directory. As an SVG, it can reference the file with no problem but when I convert the file to a PDF, it doesn't have the image but it does have the other SVG elements such as lines and text. Has anyone had this issue or know how to resolve? I'm using ImageMagick to convert but it still has that problem. See below for my controller code:

    [HttpPost]
    public void ConvertToPDF(string[] svgs, string pdfFilePath, List<string> files)
    {
        MagickReadSettings settings = new MagickReadSettings();
        using (MagickImageCollection images = new MagickImageCollection())
        {
            foreach(var s in svgs)
            {
                var fileName = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ConvertFromXMLToSvgTempPath"] + s + ".svg");

                //images.Read(fileName, settings);
                //var readSettings = new MagickReadSettings() { Format = MagickFormat.Svg };

                using (var image = new MagickImage(fileName))
                {
                    image.Format = MagickFormat.Pdf;
                }
            }
            images.Write(pdfFilePath);
        }
    }

FYI - I ended up converting the image path into Base64. The rest of the SVG converted correctly. Hope this helps anyone in the future.

Better You can try with Syncfusion HTML to PDF library.This one works better for me.

sample code

 HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
    WebKitConverterSettings settings = new WebKitConverterSettings();

    // WebKit library path
    settings.WebKitPath = @"../../QtBinaries/";

    //Assign WebKit settings to HTML converter
    htmlConverter.ConverterSettings = settings;

    //Convert a SVG file to PDF with HTML converter
    PdfDocument document = htmlConverter.Convert(@"../../Sample.svg");


    document.Save("Output.pdf");

    document.Close(true);   

To download webkit libraries WebKit HTML Converter: https://www.syncfusion.com/downloads/latest-version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM