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

标签 c# openxml docx openxml-sdk

获得了带有图像占位符的模板 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 元素,该元素包含对图像部分的引用。然后你可以使用代码的底部来调整图像大小。调整 Transform2D x 和 y 以及 Inline x 和 y 很重要,否则图像大小不会改变。

关于c# - 使用 OpenXML sdk 调整 DocX 中现有图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828091/

相关文章:

c# - 访问线程本地存储

c# - 在 Windows 7 上暂时禁用电源/重置按钮

c# - 刷新 EntityFramework 中的数据

c# - 使用 XML 文件中的数据生成 Word 文档 (docx)/基于模板将 XML 转换为 Word 文档

linux - ms dos 或 cygwin 下搜索 docx 文件的命令行工具

c# - 如何使这段代码更具可读性?

c# - Excel 如何识别日期单元格以及如何使用 OpenXml 和 C# 执行相同操作

algorithm - 从 Excel 导入中查找包含的边界区域

java - Docx4j - 如何获取 docx 复选框状态

python - 从 .docx 文件解析表格