【发布时间】:2014-06-25 14:55:59
【问题描述】:
我有一个代码,我使用 System.IO 读取字节数组格式的 docx 文档。 后来我制作了一个 docx 字节数组的流,并使用 WordprocessingDocument 来编辑 docx 流。
我在 docx 流文本中编辑/替换使用硬括号和自定义插入文本的标签。
最后,我将编辑后的 docx 流转换为新的字节数组,稍后我将其用于其他内容(例如使用字节数组创建 PDF),但之后发生的事情现在并不重要。
现在的问题是,就像我替换文本中的某些标签一样,我可以插入图像吗?最好使用 Drawing.Image,因为这就是我现在的图像格式。
澄清几点:
我知道我可以使用 Drawing.Image.Save() 保存图像,然后使用 <img href="our image url that we just saved down.png"> 编辑 [IMAGE] 标记 - 这是一个非常简单的解决方案。
但是。如果我可以避免保存不必要的文件并不得不依赖链接(如果图像消失,这不是最稳定的),我会更喜欢
但是为了避免追逐,这是我目前使用的代码:
Image image = myImage;
byte[] byteArray = System.IO.File.ReadAllBytes(fullFileNamePath); //Get our docx document as Byte Array
byte[] byteArrayAfterReading;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length); //Create a stream of the docx byte array document
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
{
Body body = wordDoc.MainDocumentPart.Document.Body;
foreach (var text in body.Descendants<Text>())
{
if (text.Text.Contains("[TEST]"))
{
text.Text = text.Text.Replace("[TEST]", "Test text here!");
}
if (text.Text.Contains("[IMAGE]"))
{
text.Text = text.Text.Replace("[IMAGE]", "Image here!");
//Here I should somehowly insert my Drawing.Image
//I could do this here but would prefer to not
//text.Text = text.Text.Replace("[IMAGE]", "<img href='imgurl.png'>");
}
}
}
byteArrayAfterReading = stream.ToArray();
}
//After here I do my convert byte array to PDF and save it
这一切都很好。我只是想找出一种在其中插入图像的好方法。
tl;博士。
我有一个 Drawing.Image,我想以某个字符串插入到我的 wordprocessingDocument.Document.Body 中,我希望不使用指向 url 的 html img 链接来执行此操作。
要更新此内容:
Bills answer,基本上是一个 MSDN 链接,显示如何插入效果很好的图像。 但是它遗漏了一些部分,例如:
如何将图像放置在某个位置,在本例中是我的 [IMAGE] 标签? (最重要的)
我宁愿不必在本地保存我的 Drawing.Image 以使用
'FileStream(fileName, FileMode.Open))'即有没有办法让我直接使用我的 Drawing.Image 而不先保存它? (不重要但更喜欢这个)在 MSDN 示例中,我的图像分辨率和纵横比发生了变化,有什么原因吗? (现在不那么重要,但将来可能会)
【问题讨论】:
-
应该有办法的。让我看看图片是如何存储在 docx 中的
-
@henrikp - 你是如何实现这一行的? //在这里我将字节数组转换为PDF并保存
标签: c# .net openxml system.drawing memorystream