asp.net-mvcsvgpdfsharpmigradoc

Embed svg in PDF using pdfsharp


Any body I want to export chart data made with d3.js in to PDF file using PDFSharp and Migradoc. I am not able to find any example. So can anybody give some example?


Solution

  • I used PDFSharp and the external program Inkscape. First, I did a function to use the command line of Inkscape (remember to install the program before trying!) to create a pdf from svg like so:

    public void ConvertSvgToPdfWithInkscape(string tempSvgFilePath, string pdfFilePath)
    {
        // Path to the Inkscape executable
        string inkscapePath = "C:/Program Files/Inkscape/bin/inkscape.exe"; // Replace with the actual path
    
        // Construct the command for converting SVG to PDF
        string command = $"\"{inkscapePath}\" \"{tempSvgFilePath}\" --export-filename=\"{pdfFilePath}\"";
    
        // Create a process to execute the Inkscape command
        using (Process process = new Process())
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
    
            process.StartInfo = startInfo;
            process.Start();
    
            // Execute the Inkscape command
            process.StandardInput.WriteLine(command);
            process.StandardInput.Flush();
            process.StandardInput.Close();
    
            // Wait for the process to finish
            process.WaitForExit();
    
            // Check if there were any errors
            string errorOutput = process.StandardError.ReadToEnd();
            if (!string.IsNullOrEmpty(errorOutput))
            {
                throw new Exception($"Inkscape Error: {errorOutput}");
            }
        }
                
    }
    

    And then I add a page to a document with the svgs using PDFSharp's AddPage method:

    using System.Diagnostics;
    using System;
    using System.Text;
    using System.Windows;
    using PdfSharp.Pdf;
    using PdfSharp.Pdf.IO;
    using System.Reflection;
    using System.IO;
    
    Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    
    string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    
    var document = new PdfDocument();
    
    string tempPDF = "temp.pdf";
    
    var svg = Directory.GetFiles(path, "*.svg", SearchOption.AllDirectories);
    
    ConvertSvgToPdfWithInkscape(svg, tempPDF);    
    
    PdfDocument inputDocument = PdfReader.Open(tempPDF, PdfDocumentOpenMode.Import);
    
    document.AddPage(inputDocument.Pages[0]);
    
    // Do whatever you need to the page of the document
    
    File.Delete(tempPDF);
    
    string fileName = path + "/output.pdf";
    
    // Save
    document.Save(fileName);
    

    If you don't need to do anything to the page of the document and it's a pdf with a single page, you can omit the PDFSharp part and just use Inkscape function.

    Check my recent question if you need to add more pages using the same method, however I am looking for a more convenient way if possible!