Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add embedded resource image to MigraDoc document

I'd like to add an 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?

like image 847
Matt Enright Avatar asked Mar 18 '11 22:03

Matt Enright


2 Answers

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).

like image 55
yvesonline Avatar answered Nov 19 '22 12:11

yvesonline


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.

like image 44
Geoff Hardy Avatar answered Nov 19 '22 12:11

Geoff Hardy