MigraDoc 中 AddImage 方法的 Image 路径可以用于 Visual Studio 项目子文件夹吗?

问题描述

以下示例显示了使用 MigraDoc 创建 PDF 的非常简单的构造。大部分内容取自 MigraDoc - Wiki 文档中提供的示例。

我已经评论了这项工作的所有最少步骤。 “AddImage”的路径指向子文件夹“Images”,它是在 Visual Studio (VS) 项目的控制台应用程序的根目录中创建的文件夹“Resources”的子文件夹。

就在昨天,最新的 MigraDoc 库已通过“NuGet”添加到 VS - 项目中。

不幸的是,如果在另一台机器上使用,应用程序创建的 PDF 输出文件没有提供的图像文件。因为执行文件无法访问在 VS 项目中创建的子文件夹。

有什么办法可以解决这个问题吗?

public class Program
{
    static void Main(string[] args)
    {
        // Create a MigraDoc document
        var document = new Document();

        // Add a section the document
        var section = document.AddSection();

        // .....


        /*
        ------------------------------- NOTE -------------------------------
        The path "../../Resources/Images/MigraDoc.png" is valid only for the developer machine!
        A copy of the content of the "Debug" or "Release" folder any where else does not show the image in the output PDF.
        Because such a copy has no access to the subfolder "/Resources/Images" of the Visual Studio project on the developer machine.
        */
        section.Headers.Primary.AddImage("../../Resources/Images/MigraDoc.png");

        // Create a renderer for PDF that uses Unicode font encoding.
        var pdfRenderer = new PdfDocumentRenderer(true);

        // Set the MigraDoc document.
        pdfRenderer.Document = document;

        // Create the PDF document.
        pdfRenderer.RenderDocument();

        // Save the PDF document...
        var filename = "Invoice.pdf";

        // Create the output directory
        Directory.CreateDirectory("PDF");

        // Create the ouptput file path
        var savePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\PDF\\" + filename;

        // Delete the output file if it already exists
        if (File.Exists(savePath))
            File.Delete(savePath);

        // Save the output file
        pdfRenderer.Save(savePath);

        // Start a the default PDF viewer from the operation system
        Process.Start(savePath);
    }
}

解决方法

..\..\ 开头的路径依赖于当前目录。对于便携式解决方案,请在部署中包含您需要的映像。

推荐用法:MigraDoc Document 类具有 ImagePath 属性。如果您的安装文件夹有一个 Images 文件夹,只需找到您的 .EXE 文件并相应地设置 ImagePath 属性。