csharp 将资源图像从嵌入式资源加载到PdfSharp / MigraDoc中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 将资源图像从嵌入式资源加载到PdfSharp / MigraDoc中相关的知识,希望对你有一定的参考价值。

/// <summary>
/// Gets "Assembly Resource" image encoded as base64 string (which MigraDoc knows how to 
/// handle), ready to be consumed by MigraDoc components. Images are located in ~/Resources/images/* 
/// and they need to be marked as "Embedded Resource" and set to "Copy if newer".
/// </summary>
/// <see cref="http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx"/>
/// <param name="imageName">Image Assembly Resource name.</param>
/// <returns></returns>
protected string GetMigraDocImage(string imageName)
{
    // Add your namespace + project path to the image you want to embed
    var assemblyResourceName = String.Format("Your.Layer.Namespace.Resources.images.{0}", imageName);
    var image = LoadAssemblyImage(assemblyResourceName);
    var imageFilename = ConvertToMigraDocFilename(image);

    return imageFilename;
}

/// <summary>
/// Loads assembly image from the project and converts it to a byte array.
/// </summary>
/// <see cref="http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx"/>
/// <param name="name">Assembly File Name.</param>
/// <returns>Image data array.</returns>
private byte[] LoadAssemblyImage(string name)
{
    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream(name))
    {
        if (stream == null)
            throw new ArgumentException("No resource with name " + name);

        int count = (int)stream.Length;
        byte[] data = new byte[count];
        stream.Read(data, 0, count);
        return data;
    }
}

/// <summary>
/// Converts image data array to base64 string. Used for integrating images into MigraDoc PDF's.
/// </summary>
/// <see cref="http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx"/>
/// <param name="image">Image data array.</param>
/// <returns>Image as base64 string.</returns>
protected string ConvertToMigraDocFilename(byte[] image)
{
    return String.Format("base64:{0}", Convert.ToBase64String(image));
}

以上是关于csharp 将资源图像从嵌入式资源加载到PdfSharp / MigraDoc中的主要内容,如果未能解决你的问题,请参考以下文章

如何将 HTML/JavaScript 从嵌入式资源加载到 winform Web 浏览器

存储 WPF 图像资源

使用 CMake 将资源(例如,着色器代码;图像)嵌入到可执行文件/库中

在 c# 中从其他资源中引用嵌入式资源

Xamarin Forms 将 ToolBarItem 图标设置为资源图像

在 C# 中从项目的资源区域加载图像