c#-使用OpenXML SDK调整DocX中现有图像的大小

得到了带有图像占位符的模板docx,该占位符已替换为正确的图片.

private void SetImagePartData(ImagePart imagePart, byte[] data)
{
    if (imagePart != null)
    {
        using (var writer = new BinaryWriter(imagePart.GetStream()))
        {
            writer.Write(data);
        }
    }
}

但保留了占位符的大小.如何将其更改为实际图像尺寸?字节数组是从服务器上的图像中提取出来的,因此大小是已知的.

解决方法:

如果您是指使用占位符的内容控件,则可以使用我曾经需要的以下代码:

//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;

但是,如果您也只是在Word文档中使用图像,则可以使用它.您只需要找到正确的Drawing元素,其中包含对imagepart的引用.然后,您可以使用代码的底部来调整图像大小.重要的是您同时调整Transform2D x和y以及Inline x和y,否则图像大小将不会更改.

上一篇:Codeforces Round #466 (Div. 2) 题解940A 940B 940C 940D 940E 940F


下一篇:获取pdf、doc/docx文本数据