About images/pdf attachment in aspose word template dynamically from backend

Could you pls help me on how to import multiple images/pdfs as an image form in Aspose.word template Linq reporting engine dynamically which are saved as bytes at backend.

@rose.thomas

Inserting Multiple Images / PDFs (as images) into a Word template with Aspose.Words .NET LINQ Reporting Engine

Below is a complete, step‑by‑step guide that shows how to:

  1. Pass a collection of byte arrays (images or PDFs saved as bytes) from your backend.
  2. Render each byte array as an image inside a Word template using the LINQ Reporting Engine.
  3. (Optional) Convert PDF pages to images first – because Word can only embed images, not PDF files.

1. Prepare the Word template

  1. Open your .docx template in Microsoft Word (or any compatible editor).

  2. Insert a MERGEFIELD where you want each image to appear, e.g.

    <<Image>>
    

    The field name (Image) must match the property name in the data source (case‑sensitive).

  3. If you need several images, you can use a repeating region:

    { FOR ImageItem IN Images }
        <<Image>>
    { END FOR }
    

    The FOR…END block tells the engine to iterate over a collection called Images.

Tip: Use the Insert → Quick Parts → Field dialog in Word and select MergeField to avoid typing errors.


2. Backend model – what the engine expects

public class ReportModel
{
    // Collection that the FOR…END block will iterate over
    public List<ImageItem> Images { get; set; }
}

public class ImageItem
{
    // The property name must be the same as the mergefield name
    public byte[] Image { get; set; }          // raw bytes of PNG/JPG/GIF
    // (optional) you can keep the original file name or type
    public string FileName { get; set; }
}

If you are dealing with PDFs, store the PDF bytes in a separate property (e.g. PdfBytes) and convert them to images before passing them to the reporting engine (see step 4).


3. Wire up the LINQ Reporting Engine with an Image‑handling callback

The LINQ Reporting Engine treats an byte[] as an image automatically if the field type is Image.
However, when you need to convert PDFs to images on‑the‑fly, you must provide a custom callback.

using Aspose.Words;
using Aspose.Words.Reporting;
using Aspose.Pdf;               // required only for PDF → image conversion
using System.IO;
using System.Drawing;

// ---------------------------------------------------------------------
// 1️⃣  Custom callback to handle image insertion
// ---------------------------------------------------------------------
public class ImageFieldCallback : IFieldMergingCallback
{
    // This method is called for every merge field
    public void FieldMerging(FieldMergingArgs args)
    {
        // -------------------------------------------------------------
        // Image field: the source value can be a byte[] (image) or a PDF
        // -------------------------------------------------------------
        if (args.FieldName == "Image")
        {
            if (args.FieldValue is byte[] rawBytes)
            {
                // ------- 1️⃣ If the bytes already represent an image -------
                using (var ms = new MemoryStream(rawBytes))
                {
                    args.ImageStream = ms;      // Aspose.Words will embed it
                }
            }
            else if (args.FieldValue is PdfDocument pdfDoc)
            {
                // ------- 2️⃣ If the source is a PDF, convert first --------
                // Convert first page (or all pages) to PNG
                var imageStream = ConvertPdfFirstPageToPng(pdfDoc);
                args.ImageStream = imageStream;
            }

            // Prevent default text merging
            args.Text = string.Empty;
        }
    }

    // -----------------------------------------------------------------
    // Helper: PDF → PNG (first page only – you can loop for all pages)
    // -----------------------------------------------------------------
    private MemoryStream ConvertPdfFirstPageToPng(PdfDocument pdf)
    {
        // Aspose.PDF for .NET conversion
        var pngDevice = new Aspose.Pdf.Devices.PngDevice(
            resolutionX: 300, resolutionY: 300,
            width: 0, height: 0,
            pageSize: Aspose.Pdf.Devices.PngDevice.PageSize.A4);

        var ms = new MemoryStream();
        pngDevice.Process(pdf.Pages[1], ms);
        ms.Position = 0;
        return ms;
    }

    // Not used – required by the interface
    public void ImageFieldMerging(ImageFieldMergingArgs args) { }
}

// ---------------------------------------------------------------------
// 2️⃣  Build the report
// ---------------------------------------------------------------------
public void BuildWordReport(ReportModel model, string templatePath, string outputPath)
{
    // Load the template
    var doc = new Document(templatePath);

    // Create the reporting engine
    var engine = new ReportingEngine
    {
        // Attach our callback so we can control image insertion
        FieldMergingCallback = new ImageFieldCallback()
    };

    // Run the engine – the second argument can be any object (model)
    engine.BuildReport(doc, model, "ReportData");

    // Save the generated document
    doc.Save(outputPath);
}

Key points in the code above

What Explanation
FOR ImageItem IN Images The engine iterates over model.Images.
Image mergefield Must match the property name (Image) of ImageItem.
IFieldMergingCallback Gives you full control over the data that is inserted.
args.ImageStream = ms Directly supplies the image stream to Aspose.Words.
PDF conversion Performed with Aspose.PDF for .NET (PngDevice). Convert each PDF page you need to a PNG (or JPEG) stream, then pass that stream to args.ImageStream.

4. Converting PDFs to images (if you need to embed PDFs)

Word cannot embed a PDF as an image directly, so you have to render the PDF pages first.

// Example: convert all pages of a PDF to a List<byte[]> (PNG)
public List<byte[]> PdfToPngPages(byte[] pdfBytes)
{
    var pdf = new Aspose.Pdf.Document(new MemoryStream(pdfBytes));
    var pngDevice = new Aspose.Pdf.Devices.PngDevice(300, 300);

    var pagesImages = new List<byte[]>();
    foreach (var page in pdf.Pages)
    {
        var ms = new MemoryStream();
        pngDevice.Process(page, ms);
        pagesImages.Add(ms.ToArray());
    }
    return pagesImages;
}

You can then create multiple ImageItem objects (one per rendered PDF page) and add them to model.Images.


5. Putting everything together (sample usage)

// ---------------------------------------------------------------
// 1️⃣  Load image/PDF bytes from your data store (DB, file system…)
// ---------------------------------------------------------------
byte[] img1 = File.ReadAllBytes(@"C:\Images\photo1.jpg");
byte[] img2 = File.ReadAllBytes(@"C:\Images\photo2.png");
byte[] pdfBytes = File.ReadAllBytes(@"C:\Docs\sample.pdf");

// ---------------------------------------------------------------
// 2️⃣  Convert PDF → images (optional)
// ---------------------------------------------------------------
var pdfPages = PdfToPngPages(pdfBytes);   // returns List<byte[]>

// ---------------------------------------------------------------
// 3️⃣  Build the data model
// ---------------------------------------------------------------
var model = new ReportModel
{
    Images = new List<ImageItem>()
    {
        new ImageItem { Image = img1,  FileName = "photo1.jpg" },
        new ImageItem { Image = img2,  FileName = "photo2.png" }
    }
};

// Add each PDF page as a separate image item
foreach (var pageBytes in pdfPages)
{
    model.Images.Add(new ImageItem { Image = pageBytes, FileName = "pdfPage.png" });
}

// ---------------------------------------------------------------
// 4️⃣  Generate the Word document
// ---------------------------------------------------------------
string templatePath = @"C:\Templates\MyReportTemplate.docx";
string outputPath   = @"C:\Generated\ReportResult.docx";

BuildWordReport(model, templatePath, outputPath);

The resulting ReportResult.docx will contain all supplied images, including the PDF pages rendered as images, placed exactly where the <<Image>> mergefield appears in the template.


:books: Useful Links from Aspose Documentation

Topic Link
LINQ Reporting Engine – Getting Started https://docs.aspose.com/words/net/linq-reporting-engine/
Working with MergeFields (Image insertion) https://docs.aspose.com/words/net/working-with-mergefields/
Custom IFieldMergingCallback example https://docs.aspose.com/words/net/custom-field-merging-callback/
Convert PDF pages to images (Aspose.PDF) https://docs.aspose.com/pdf/net/convert-pdf-pages-to-images/
Insert image from stream with DocumentBuilder (alternative) https://docs.aspose.com/words/net/insert-an-image-into-a-document/

:white_check_mark: Quick checklist before running

  • References: Add NuGet packages Aspose.Words and Aspose.PDF (if you need PDF → image conversion).
  • Template field names must exactly match the property names (Image).
  • Byte arrays must be in a supported image format (PNG, JPEG, GIF, BMP, TIFF).
  • For PDFs, ensure you have Aspose.PDF for .NET license if you need it in production; otherwise the free evaluation works for testing.

If you run into any specific error (e.g., “Image format not supported”, “Field not found”), please share the exception details and a snippet of your template. I’ll be happy to help you troubleshoot further!

@rose.thomas Unfortunately, your requirements are no clear enough. If possible, please provide you template, sample date and expected output. We will check your documents and data and provide you more information.