使用 pdfsharp 将 svg 嵌入 PDF

问题描述 投票:0回答:1

我想使用 PDFSharp 和 Migradoc 将使用 d3.js 制作的图表数据导出到 PDF 文件的任何主体。我找不到任何例子。那么有人可以举个例子吗?

asp.net-mvc svg pdfsharp migradoc
1个回答
-2
投票

我使用了

PDFSharp
和外部程序
Inkscape
。首先,我做了一个使用 Inkscape 命令行的功能(记住在尝试之前安装该程序!)从 svg 创建 pdf,如下所示:

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}");
        }
    }
            
}

然后我使用 PDFSharp 的

AddPage 
方法将页面添加到带有 svgs 的文档中:

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(list[ev], 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);

如果您不需要对文档的页面进行任何操作,并且是单页的 pdf,则可以省略 PDFSharp 部分,仅使用 Inkscape 功能。

如果您需要使用相同的方法添加更多页面,请检查我最近的问题,但是如果可能的话,我正在寻找更方便的方法!

© www.soinside.com 2019 - 2024. All rights reserved.