我目前正在使用图片内容控件插入图像,但似乎有一个明显的限制(根据控件的性质)只能插入 1 张图像。
如何使用 OpenXML SDK (2+) 在设定位置添加多张图片?
我确实尝试了 BookMarks,但这似乎不起作用,只会导致文档损坏。
我已经有相当多的代码来构建现有文档,因此考虑 mHtml 路由不是一个选项。
最后我确实尝试了 OpenXML SDK Productivity Tool,但仍然看不到如何在设定位置插入多个图像。
最佳答案
问题是图片内容控件都有一些指向相同“空白”图像的 id。您必须将每个图像的资源 ID 分配给每个内容控件的 blip.embed 属性
这篇文章为您提供了一个简短而有效的方法
Open XML – Setting multiple Picture Content Controls by Tag name, without going crazy
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
// Select element containing picture control and get the blip element
Bitmap image = new Bitmap(@"F:insert_me.jpg");
SdtElement controlBlock = _mainDocumentPart.Document.Body
.Descendants<SdtElement>()
.Where
(r =>
r.SdtProperties.GetFirstChild<Tag>().Val == tagName
).SingleOrDefault();
// Find the Blip element of the content control.
A.Blip blip = controlBlock.Descendants<A.Blip>().FirstOrDefault();
// Add image and change embeded id.
ImagePart imagePart = _mainDocumentPart
.AddImagePart(ImagePartType.Jpeg);
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
imagePart.FeedData(stream);
}
blip.Embed = _mainDocumentPart.GetIdOfPart(imagePart);
关于c# - OpenXml 多图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707041/