I have a .docx template with a "Picture Content Control" which is placed inside a shape. I've successfully inserted an user selected image to that particular area, as the user selected images's got different sizes I'm looking for a solution 开发者_运维技巧to programmatically adjust the height and width scale of both "Picture Content Control" and the container (Shape). I'm using this solution to insert images to my .docx template: http://www.codeproject.com/KB/office/Word_2007_Images.aspx
For these things, I often find the most useful answer can come from recording a macro, doing what you want the program to do, then reviewing the code generated by the macro and tweaking it as necessary. The macro will show you how to use the Word objects to do what you want to do.
This caused me a great deal of trouble too, but I found the solution:
//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;
After all this I choose to remove the content control and insert the code from the sdtContent just as a run in my paragraph but this is optional of course :)
精彩评论