【问题标题】:OpenXML Images added with AddImagePart not showing up in document.xml.rels使用 AddImagePart 添加的 OpenXML 图像未显示在 document.xml.rels 中
【发布时间】:2014-01-27 06:00:26
【问题描述】:

我正在尝试使用 OpenXML SDK 2.5 将图像添加到现有的 Word 2010 文档中。但是当我添加图像时,图像不会被嵌入。当我打开文档时,图像显示带有红十字的占位符(好像找不到图像)。 我正在使用以下代码:

string mimetype = String.Empty;
// :
//Find mime type of the image here
// :
imagePart = wpd.MainDocumentPart.AddImagePart(mimetype);

using (FileStream stream = new FileStream(filename, FileMode.Open))
{
    image = new Bitmap(stream);
    cy = Convert.ToUInt32(image.PhysicalDimension.Height);
    cx = Convert.ToUInt32(image.PhysicalDimension.Width);
    imagePart.FeedData(stream);
    stream.Close();
 }
 Paragraph para = FindParagraphInAppendix(....); //Find the paragraph to add
 if (para != null)
    AddImageToParagraph(para, wpd.MainDocumentPart.GetIdOfPart(imagePart),txt, filename,cx,cy);
 else
      wpd.MainDocumentPart.Document.Body.Append(GetImageWithPara(wpd.MainDocumentPart.GetIdOfPart(imagePart), filename, cx, cy));
wpd.Package.CreateRelationship(imagePart.Uri, System.IO.Packaging.TargetMode.External,wpd.MainDocumentPart.GetIdOfPart(imagePart));
wpd.MainDocumentPart.Document.Save();

在 AddImageToParagraph 的代码中,我将图像添加如下:

Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = relationshipid,
                             CompressionState = A.BlipCompressionValues.Print };
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();

当我打开使用 Winzip 生成的文件时,document.xml.rels 文件不包含与嵌入图像关联的关系 ID。

当我打开使用 OpenXML 生产力工具并验证 XML 时,我收到错误:“属性 'hxxp://schemas.openxmlformats..../relationships:embed' 引用的关系 'R75a8cc179...' 确实不存在 你能帮忙吗?

谢谢!

【问题讨论】:

  • 您能否发送生成的 docx 以查看究竟是什么问题?
  • 无法真正上传文档。但奇怪的是 imagePart.AddImagePart 没有在生成的 document.xml.rels 中创建<Relationship> 标记。我看到的所有例子似乎都在做我正在做的事情......
  • 附加信息:wpd.GetReferenceRelationship(wpd.MainDocumentPart.GetIdOfPart(imagePart)) 抛出 System.Generic.Collections.KeyNotFoundException。

标签: xml image openxml docx


【解决方案1】:

我终于明白了 问题出在编辑 MainDocumentPart 之后,我只调用了 wordProcessingDocument.MainDocumentPart.Save()。我没有调用Close() 方法。由于这个原因,ImagePart 关系没有被提交到包中。我认为Close() 方法导致关系被“写入”到docx 包的word\_rels\document.xml.rels 部分!

【讨论】:

  • 谢谢你,你刚刚救了我的命……或者至少是其中的一大部分 :)
  • MainDocumentPart 没有保存方法,也没有关闭方法。我认为您使用了文档类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
相关资源
最近更新 更多