使用OpenXML SDK调整DocX中现有图像的大小 [英] Resize existing image in DocX using OpenXML sdk

查看:150
本文介绍了使用OpenXML SDK调整DocX中现有图像的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有图像占位符的模板docx已替换为正确的图片.

Got template docx with image placeholder which replaced by correct picture.

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

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

but it preserves placeholder size. How to change it to actual image size? Byte array is aqquared from image on server, so size is known.

推荐答案

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

If you mean a content control with your placeholder you can use following code I once needed:

//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,否则图像尺寸将不会更改.

But you can use it if you are just using an image in your word document too. You just need to locate the correct Drawing element which contains the reference to your imagepart. Then you can use the bottom part of the code to adjust the image size. It's important you adjust both the Transform2D x and y as well as the Inline x and y or the image size won't be changed.

这篇关于使用OpenXML SDK调整DocX中现有图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆