首页 > 解决方案 > 使用 OpenXML 的 Vanish 类隐藏 WordProcessingDocument 对象中的 HTML 部分

问题描述

我正在尝试将 HTML 页面附加到 DocM 文件中,并隐藏整个内容。据我了解,我需要使用 Vanish 类(https://docs.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.vanish?view=openxml-2.8.1)来实现这一点。

AltChunk我使用此处提供的代码将 HTML 内容流式传输到: https ://stackoverflow.com/a/18152334/1243462 。然后我尝试将 altchunk 附加到Vanish类的实例,然后将该Vanish对象添加到 MainBodyPart,如下所示:

Vanish hideThisHTMLContent = new Vanish();
string altChunkId = "altChunk1";

// Create alternative format import part.
AlternativeFormatImportPart chunk = copy.MainDocumentPart.AddAlternativeFormatImportPart
  (AlternativeFormatImportPartType.Html, altChunkId);

using MemoryStream htmlContentStream = new MemoryStream(new UTF8Encoding(true)
  .GetPreamble().Concat(Encoding.UTF8.GetBytes(attachmentContent)).ToArray());

// Feed HTML data into the chunk.
chunk.FeedData(htmlContentStream);
AltChunk altChunk = new AltChunk
{
    Id = altChunkId
};

//Hide the HTML alt chunk by appending it as a child to the hidden element
hiddenPart.AppendChild(altChunk);

//Append hidden part to MainDocumentPart.Body
copy.MainDocumentPart.Document.Body.Append(hiddenPart);

我的理解是需要这个附加,以便 HTML 内容“继承”对象的隐藏属性。此代码编译,但我得到一个运行时错误,如下所示:

System.InvalidOperationException
HResult=0x80131509
Message=Non-composite elements do not have child elements.
Source=DocumentFormat.OpenXml
StackTrace:
 at DocumentFormat.OpenXml.OpenXmlElement.AppendChild[T](T newChild)
 at ApproachTwoAccessWordElements.Program.doUsingHiddenClass() in 
  C:\Users\sraje\source\repos\ApproachTwoAccessWordElements\Program.cs:line 55
 at ApproachTwoAccessWordElements.Program.Main(String[] args) in 
  C:\Users\sraje\source\repos\ApproachTwoAccessWordElements\Program.cs:line 16

有人可以帮忙吗?我也无法找到如何使用此属性正确隐藏部分的代码示例

标签: c#ms-wordopenxmlopenxml-sdk

解决方案


推荐阅读