惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
B
Blog
P
Proofpoint News Feed
美团技术团队
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
有赞技术团队
有赞技术团队
小众软件
小众软件
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
H
Help Net Security
罗磊的独立博客
L
LangChain Blog
GbyAI
GbyAI
腾讯CDC
T
The Blog of Author Tim Ferriss
Microsoft Security Blog
Microsoft Security Blog

博客园 - soulsjie

一种在winfrom窗体中显示计算公式的解决方案 winform窗体DataGridView合并单元格处理 C#GDI+阴影笔刷样式HatchStyle探讨 C#代码混淆工具ConfuserEx的使用 C#获取对象实体的键值对信息 C#将Winform上的TextBox和ComBox的值导入和导出 C#使用Aspose.Words将Spread表格插入到Word中 C# Aspose.Words将word中自定义的标签进行替换 Python文件操作基础方法 C# 将项目资源文件保存到磁盘上 SqlSugar数据库辅助类 使用存储过程备份MS SQLServer数据库 案例3:JAVA GUI 随机点名程序 案例2:JAVA GUI 简易计算器 ArcGIS JS API 添加要素图层 点击时获取图层属性 ArcGIS JS API 将天地图设置为底图 HTML5PLUS实现类似右侧弹出菜单 SqlSugar各数据库连接串 案例1:JAVAGUI用户管理
Aspose.Words在指定位置插入图片、调整图片大小
soulsjie · 2023-05-24 · via 博客园 - 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;
    }
}