C# 使用 DocX 库向 .docx 文件插入并排图片的问题咨询
DocX 实现两张图片水平并排的两种可行方案
DocX 原生没有提供直接插入并排图片的API,以下两种是经过验证的稳定实现方式:
方案1:无边框表格布局(兼容性最高,推荐)
利用1行2列的无边框表格作为布局容器,效果和普通并排内容完全一致,不会出现版本兼容导致的排版偏移问题。
实现步骤:
- 插入1行2列的表格,关闭所有边框显示
- 分别向两个单元格插入目标图片,可按需调整图片大小、单元格内边距控制图片间距
代码示例:
using Novacode; using System.Drawing; // 初始化文档 using DocX document = DocX.Create("测试文档.docx"); // 定义图片路径 string imgPath1 = "图片1路径.png"; string imgPath2 = "图片2路径.png"; // 创建1行2列的表格 Table imgTable = document.AddTable(1, 2); // 关闭所有表格边框 imgTable.SetBorder(TableBorderType.Top, new Border(BorderStyle.None, 0, Color.Transparent)); imgTable.SetBorder(TableBorderType.Bottom, new Border(BorderStyle.None, 0, Color.Transparent)); imgTable.SetBorder(TableBorderType.Left, new Border(BorderStyle.None, 0, Color.Transparent)); imgTable.SetBorder(TableBorderType.Right, new Border(BorderStyle.None, 0, Color.Transparent)); imgTable.SetBorder(TableBorderType.InsideH, new Border(BorderStyle.None, 0, Color.Transparent)); imgTable.SetBorder(TableBorderType.InsideV, new Border(BorderStyle.None, 0, Color.Transparent)); // 插入第一张图片到第一个单元格 Image img1 = document.AddImage(imgPath1); Picture pic1 = img1.CreatePicture(); // 按需调整图片大小 pic1.Width = 200; pic1.Height = 150; imgTable.Rows[0].Cells[0].Paragraphs[0].AppendPicture(pic1); // 调整单元格内边距控制间距 imgTable.Rows[0].Cells[0].MarginRight = 10; // 插入第二张图片到第二个单元格 Image img2 = document.AddImage(imgPath2); Picture pic2 = img2.CreatePicture(); pic2.Width = 200; pic2.Height = 150; imgTable.Rows[0].Cells[1].Paragraphs[0].AppendPicture(pic2); imgTable.Rows[0].Cells[1].MarginLeft = 10; // 把表格插入到文档 document.InsertTable(imgTable); // 保存文档 document.Save();
方案2:浮动图片手动定位
适合需要精确控制图片位置的场景,通过设置图片的文本环绕方式和水平偏移量实现并排。
代码示例:
using Novacode; using DocX document = DocX.Create("测试文档.docx"); string imgPath1 = "图片1路径.png"; string imgPath2 = "图片2路径.png"; // 插入第一张图片,设置为方形环绕 Image img1 = document.AddImage(imgPath1); Picture pic1 = img1.CreatePicture(150, 200); pic1.WrapText = WrapText.Square; // 设置第一张图片的水平位置为距离页面左边缘50磅 pic1.HorizontalPosition = 50; document.InsertParagraph().AppendPicture(pic1); // 插入第二张图片 Image img2 = document.AddImage(imgPath2); Picture pic2 = img2.CreatePicture(150, 200); pic2.WrapText = WrapText.Square; // 第二张图片水平位置设置为第一张图片右侧,偏移量可根据实际图片宽度调整 pic2.HorizontalPosition = 270; document.InsertParagraph().AppendPicture(pic2); document.Save();
效果参考
两种方案都可以实现预期的并排布局效果,优先选择方案1,排版稳定性更高,不会因为后续编辑正文内容导致图片位置偏移。
内容的提问来源于stack exchange,提问作者Åfsħąl Ãtħąr
相关产品推荐
相关产品推荐

