s
o
u
l
s
j
i
e

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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宽

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
    }
}

  

posted @   soulsjie  阅读(2699)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
你累吗?累就对了,当你觉得累时证明你在走上坡路!-----NotFoundObject - 2016-12-14 08:43
点击右上角即可分享
微信分享提示