0

I am attempting to append an HTML page into a DocM file, and have the entire content hidden. As I understand, I need to use the Vanish class (https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.vanish?view=openxml-2.8.1) to achieve this.

I streamed the HTML content into an AltChunk using the code provided here: https://stackoverflow.com/a/18152334/1243462 . I then try to append the altchunk to an instance of the Vanish class, and then add that Vanish object to the MainBodyPart, like so:

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);

My understanding is that this append is needed so that the HTML content "inherits" the hidden property of the object. This code compiles, but I get a runtime error, as shown below:

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

Can someone please help with this? I am also unable to find code samples for how to properly hide sections using this property

shikharraje
  • 127
  • 1
  • 17
  • 1
    You cannot place `AltChunk` inside the `Vanish`, this is an empty element (has no child elements) that must be placed inside the `RunProperties` element. Instead, how about you try modifying your HTML, try adding "display:none" to its HTML or BODY element. – Mario Z Mar 29 '21 at 08:54
  • Thanks for the advice. Actually, there is a VBA control in the document, which toggles visible text as on and off in the DocM file. Would modifying the HTML insert all the content as hidden, but still allow the Vanish property to be toggled via the VBA control? – shikharraje Apr 05 '21 at 07:24

0 Answers0