以编程方式更改Word文档中的图像大小

时间:2010-12-29 06:38:32

标签: .net xml image

我有一个带有“图片内容控件”的.docx模板,该模板放在一个形状中。我已经成功地将用户选择的图像插入到该特定区域,因为用户选择的图像具有不同的尺寸我正在寻找一种解决方案来以编程方式调整“图片内容控件”和容器(形状)的高度和宽度比例。 我正在使用此解决方案将图像插入我的.docx模板: http://www.codeproject.com/KB/office/Word_2007_Images.aspx

2 个答案:

答案 0 :(得分:0)

对于这些事情,我经常发现最有用的答案可能来自录制宏,执行您希望程序执行的操作,然后查看宏生成的代码并根据需要进行调整。该宏将向您展示如何使用Word对象来执行您想要执行的操作。

答案 1 :(得分:0)

这也给我带来了很多麻烦,但我找到了解决方案:

//Get SdtElement (can be a block, run... so I use the base class) with corresponding Tag
SdtElement block = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>()
   .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag)

//Get First drawing Element and get the original sizes of placeholder SDT
//I use SDT placeholder size as maximum size to calculate picture size with correct ratios
Drawing sdtImage = block.Descendants<Drawing>().First();
double sdtWidth = sdtImage.Inline.Extent.Cx;
double sdtHeight = sdtImage.Inline.Extent.Cy;
double sdtRatio = sdtWidth / sdtHeight;

*Calculate final width/height of image*

//Resize picture placeholder
sdtImage.Inline.Extent.Cx = finalWidth;
sdtImage.Inline.Extent.Cy = finalHeight;

//Change width/height of picture shapeproperties Transform
//This will override above height/width until you manually drag image for example
sdtImage.Inline.Graphic.GraphicData
        .GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
        .ShapeProperties.Transform2D.Extents.Cx = finalWidth;
sdtImage.Inline.Graphic.GraphicData
        .GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
        .ShapeProperties.Transform2D.Extents.Cy = finalHeight;

毕竟我选择删除内容控件并插入sdtContent中的代码,就像我的段落中的运行一样,但这当然是可选的:)