c# - OpenXml 多图像

标签 c# .net ms-office openxml

我目前正在使用图片内容控件插入图像,但似乎有一个明显的限制(根据控件的性质)只能插入 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/

相关文章:

c# - Visual Studio 2010 中的 Word 2007 文档

c# - MS Word 格式数据系列线帽类型

vba - Visio 使用 VBA 更改形状数据/属性

excel - 如何在 Microsoft Excel 中的公式后附加多行文本?

c# - 使用多行时 C# 中的慢速字符串格式化

c# - 为什么我不能从通用对象运行以下方法?

c# - 一个字符前后出现的次数相同

.net - WM_SETREDRAW 并丢失 z 顺序/焦点

.net - 文化和 UICulture 有什么区别?

c# - 获取 LINQ 之前的子集 x 元素和 LINQ 之后的 x 元素