MiniWord
MiniWord copied to clipboard
Inserting image suggestion.
MiniWord inserts images like:
ReportData["Photo"] = new MiniWordPicture() { Path="photo.jpg", Width = 200, Height = 150 };
But this gives you no control over styling in the .docx template — which breaks WYSIWYG template authoring.
Instead of using a text placeholder like {{Photo}}, it is better to:
-
Add an actual image placeholder (invisible dummy image) in the Word template
-
Let the C# code replace that image in-place, preserving its size and formatting
Currently I add post processing to MiniWord with code:
private static void ReplaceImagesByAltText(WordprocessingDocument wordDoc, IDictionary imageMap)
{
//using var wordDoc = WordprocessingDocument.Open(docPath, true);
var mainPart = wordDoc.MainDocumentPart;
var drawings = mainPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Drawing>().ToList();
foreach (var drawing in drawings)
{
var docProps = drawing.Descendants<DocProperties>().FirstOrDefault();
var altText = docProps.Description.ToString();
if (docProps == null || !imageMap.Contains(altText)) continue;
byte[] imageData = null;
//consider to use byte array instead of MiniWordPicture for simplitcity
if(imageMap.GetValueByKey(altText) is MiniSoftware.MiniWordPicture pic) imageData = pic.Bytes;
if (imageData is byte[] image && image.Length > 0)
{
var blip = drawing.Descendants<Blip>().FirstOrDefault();
if (blip == null) continue; // Skip if no image
var imagePartId = blip.Embed.Value;
var imagePart = (ImagePart)mainPart.GetPartById(imagePartId);
using var stream = imagePart.GetStream(FileMode.Create, FileAccess.Write);
stream.Write(image, 0, image.Length);
}
}
}
The template image is replacing by running report image
@EricNgo1972 Good suggestion! would you like to try PR? Now I'm developing AI tool...