user2185592
user2185592

Reputation: 388

Laying out images in Word document programmatically

I'm trying to generate a Word document through my application coded in WPF. In that document, I also need to layout few images along with caption as shown in the image below.

enter image description here

All the images are stored in database as base64 string. I'm able to load the images as "BitmapImage" object in the document however not sure how to layout the images as shown in image. Code snippet to load the images in document is as below :

        var bookmarks = wordDoc.Bookmarks;
        var range = bookmarks["ExternalImage"].Range;
        foreach (var image in ExternalImages) // here image is "BitmapImage" object
        {
            float scaleHeight = (float)250 / (float)image.Image.PixelHeight;
            float scaleWidth = (float)250 / (float)image.Image.PixelWidth;
            var min = Math.Min(scaleHeight, scaleWidth);
            var bitmap = new TransformedBitmap(image, new ScaleTransform(min, min));   
            System.Windows.Clipboard.SetImage(bitmap);
            range.Paste();
        }

How can I lay out the images as shown in image above along with caption? Note that I'm not loading images from file but from memory object.

Upvotes: 0

Views: 192

Answers (1)

user2185592
user2185592

Reputation: 388

Based on the direction provided by @CindyMeister in comments, following is the working code snippet to layout the images using code :

    imageTable = wordDoc.Tables.Add(sel.Range, rows, cols, ref oMissing, ref oMissing);
    imageTable.AllowAutoFit = true;
    row = 1; col = 1;
    foreach (var image in Images)
   {
      float scaleHeight = (float)475 / (float)image.PixelHeight;   
     // here 475 is approx image size I want in word document
     float scaleWidth = (float)475 / (float)image.PixelWidth;
     var min = Math.Min(scaleHeight, scaleWidth);

     var bitmap = new TransformedBitmap(image, new ScaleTransform(min, min));

     System.Windows.Clipboard.SetImage(bitmap);

     //more efficient/faster in C# if you don't "drill down" multiple times to get an object
     Word.Cell cel = imageTable.Cell(row, col);
     Word.Range rngCell = cel.Range;
     Word.Range rngTable = imageTable.Range;

     rngCell.Paste();
     cel.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
     rngCell.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; 
     // set caption below image
     rngTable.ParagraphFormat.SpaceAfter = 6;
     rngCell.InsertAfter(image.Caption);
     rngTable.Font.Name = "Arial Bold";
     row++;
  }

This code I have posted for reference, only, to let people have some starting point. Any suggestions welcome.

Upvotes: 1

Related Questions