Aspose.Words在指定位置插入图片、调整图片大小

发布时间 2023-05-24 09:54:10作者: soulsjie

在word模板中定义字符串,如“{图片1}”,用于定位图片插入的位置。原理:遍历所有段落,在指定位置插入图片,再将定位字符串替换为空

NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph paragraph in paragraphs)
{
    int index = paragraph.GetText().IndexOf("{图片1}");
    if (index >= 0)
    {
        string imgPath = "Tu1.png";
        if (File.Exists(imgPath)) 
        {
            // 创建DocumentBuilder对象
            DocumentBuilder builder = new DocumentBuilder((Document)paragraph.Document);
            // 在段落中插入图片
            builder.MoveTo(paragraph);
            builder.Write(paragraph.GetText().Substring(0, index));
            builder.InsertImage(imgPath);
            builder.Write(paragraph.GetText().Substring(index + "{图片1}".Length));
        }
        paragraph.Range.Replace("{图片1}", "", false, false);
    }
    //插入其它图片
    //...
}

  处理完所有图片后统一将所有图片宽度统一设为400px宽

foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
{
    if (shape.HasImage)
    {
        // 计算图片原始宽高比例
        double aspectRatio = (double)shape.ImageData.ImageSize.WidthPoints / shape.ImageData.ImageSize.HeightPoints;
        // 计算高度
        int height = (int)(400 / aspectRatio);
        // 设置宽高
        shape.Width = 400;
        shape.Height = height;
    }
}