我正在尝试通过我在WPF中编码的应用程序生成word文档。在该文档中,我还需要布置一些图像以及标题,如下图所示。
所有图像都作为base64字符串存储在数据库中。我能够将图像作为“BitmapImage”对象加载到文档中,但不确定如何布局图像,如图所示。用于加载文档中图像的代码片段如下:
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();
}
我需要有关如何布局图像的帮助,如上图所示以及标题。请注意,我没有从文件加载图像,而是从内存对象加载图像。
谢谢,
答案 0 :(得分:1)
根据@CindyMeister在评论中提供的方向,以下是使用代码布局图像的工作代码片段:
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++;
}
这个代码我发布仅供参考,让人们有一些起点。欢迎任何建议。