【发布时间】:2021-04-10 11:05:42
【问题描述】:
所以我需要生成一个 docx 文件用于报告目的。该报告包含文本、表格和大量图像。
到目前为止,我设法添加了文本和表格(并使用 xslt 转换根据我的 xml 内容填充它)。
但是,我坚持添加图像。我找到了一些如何使用 C# 添加图像的示例,但我认为这不是我需要的。我需要使用我的 xslt 格式化文档并将图像添加到正确的位置(例如在表格单元格中)。是否可以使用 xslt 添加一个容器,该容器使用文件路径来显示/嵌入类似于 html 中的<img> 标记的图像?
我知道 docx 格式基本上是一个包含文件结构的 zip,要嵌入图像,我也应该将它添加到这个文件结构中。
感谢任何示例或参考。
让您了解我的代码:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltFile);
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(stringWriter);
transform.Transform(xmlFile, xmlWriter);
XmlDocument newWordContent = new XmlDocument();
newWordContent.LoadXml(stringWriter.ToString());
File.Copy(docXtemplate, outputFilename, true);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outputFilename, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
Body body = new Body(newWordContent.DocumentElement.InnerXml);
DocumentFormat.OpenXml.Wordprocessing.Document document = new DocumentFormat.OpenXml.Wordprocessing.Document(body);
document.Save(mainPart);
}
它基本上替换了现有 docx 文件的正文。这使我能够使用所有格式等。 xslt文件是通过调整docx中的document.xml文件生成的。
更新
好的,所以我想出了如何将图像添加到 docx 文件目录,见下文
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outputFilename, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(imageFile, FileMode.Open))
{
imagePart.FeedData(stream);
}
Body body = new Body(newWordContent.DocumentElement.InnerXml);
DocumentFormat.OpenXml.Wordprocessing.Document document = new
DocumentFormat.OpenXml.Wordprocessing.Document(body);
document.Save(mainPart);
}
这会将图像添加到 docx 结构中。我还检查了关系,这存在于“document.xml.rels”文件中。当我使用这个 id 并在我的 xslt 中使用它来将图像添加到文档中(用于测试)时,我确实看到了使用 Word 打开时图像应该位于的区域,但是它说:无法显示带有红十字的图像。
我注意到的一个区别是原始docx中的图像保存在“word\media”中,而带有上述代码的添加图像被添加到“media”中。不确定这是不是问题
【问题讨论】:
-
这能回答你的问题吗? Inserting images from XML to XSL document
-
不,这不能回答我的问题。他们正在创建一个 html 页面,我想创建一个 *.docx 文件。