开发者

Add embedded resource image to MigraDoc document

开发者 https://www.devze.com 2023-02-17 14:52 出处:网络
I\'d like to add a开发者_如何学Cn image to the header of a MigraDoc document, but hardcoding a filesystem path in the document generation is slightly problematic for a number of issues - not the least

I'd like to add a开发者_如何学Cn image to the header of a MigraDoc document, but hardcoding a filesystem path in the document generation is slightly problematic for a number of issues - not the least of which is that it makes me a little queasy, but also, to keep deployment simple(r).

It would seem to me ideal if I could embed the image as a resource in the assembly, and just extract it when it was needed for the PDF, but there doesn't seem ot be any straightforward or built-in way to do this. Any tricks or ideas?


PDFSharp/MigraDoc 1.50 includes another way to do this. From the MigraDoc wiki:

With PDFsharp 1.50 beta 2, a new feature was added: MigraDoc now accepts filenames that contain BASE64-encoded images with the prefix "base64:". In this case, the filename does not refer to a file, the filename contains all the bits of the bitmap in an ASCII string with the BASE64 encoding.


No, MigraDoc does not allow this. There is a hack, but it works only if you use ASP .NET and you are not using the document preview. See these threads in the official forum which explain the problem in detail:

  • http://forum.pdfsharp.net/viewtopic.php?f=2&t=1398
  • http://forum.pdfsharp.net/viewtopic.php?f=2&t=1292

You can use the embedded resources via a workaround, i.e. save them temporarily and delete them via the dispose method and the destructor after you are finished. Example:

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("pack://application:,,/Resources/temp.png");
bi.EndInit();
PngBitmapEncoder pbe = new PngBitmapEncoder();
pbe.Frames.Add(BitmapFrame.Create(bi));
using (FileStream fs = new FileStream("temp.png", FileMode.Create))
{
    pbe.Save(fs);
}

Then you can use it via MigraDocObject.AddImage("temp.png"); But be sure to delete the image afterwards or add a check if the image already exists and if it has the correct file size (in case the user replaced it).

0

精彩评论

暂无评论...
验证码 换一张
取 消