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?
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:
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With