gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:23:01 27 4
gpt4 key购买 nike

获得了带有图像占位符的模板 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com