I would like to create a document based on a template. This template contains a TOC which was added using Word. Because TOC’s can not be updated by Aspose is has no use when I save the document to Aspose.PDF (all of the headings added runtime are not shown in the TOC).
In order to have a correct TOC in PDF I like to find the dynamic TOC in my document, delete it and add a static TOC (using documentbuilder.WriteLn()). Unfortunately I get an error when saving the document to a stream.
The error I get is:
System.InvalidOperationException: Stack empty.
at System.Collections.Stack.Pop()
at ?.?.VisitFieldEnd(FieldEnd fieldEnd)
at Aspose.Words.Fields.FieldEnd.Accept(DocumentVisitor visitor)
at Aspose.Words.CompositeNode.?(DocumentVisitor ?)
at Aspose.Words.Paragraph.Accept(DocumentVisitor visitor)
at Aspose.Words.CompositeNode.?(DocumentVisitor ?)
at Aspose.Words.Body.Accept(DocumentVisitor visitor)
at Aspose.Words.CompositeNode.?(DocumentVisitor ?)
at Aspose.Words.Section.Accept(DocumentVisitor visitor)
at Aspose.Words.CompositeNode.?(DocumentVisitor ?)
at Aspose.Words.Document.Accept(DocumentVisitor visitor)
at ?.?.?(? ?)
at Aspose.Words.Document.Save(Stream stream, SaveFormat saveFormat)
at TestAspose.Program.CreatePdf(Document doc) in d:\_tjip\TestAspose\TestAspo
se\Program.cs:line 75
at TestAspose.Program.Main(String[] args) in d:\_tjip\TestAspose\TestAspose\P
rogram.cs:line 38
Below is a part of the code I use (full solution is added as an attachment):
Document doc = new Document(template);
// Find current dynamic TOC in document en delete it (it has no use in PDF when new headings are
// added to the document, since there is no automatic update for them)
Node dynamicTOC = GetDynamicTOC(doc);
Aspose.Words.Paragraph parent = (Aspose.Words.Paragraph)dynamicTOC.ParentNode;
parent.RemoveAllChildren();
// Add node to paragraph (needed for Office Word to work)
Node insertAfterNode = parent.AppendChild(new Run(doc));
// ... add new static TOC to paragraph
// Create PDF object and save to file
Pdf pdf = CreatePdf(doc);
pdf.Save(filename);
-----------------------------------------------------------------------
private static Pdf CreatePdf(Document doc)
{
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.AsposePdf);
stream.Seek(0, SeekOrigin.Begin);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
Pdf pdf = new Pdf();
pdf.IsImagesInXmlDeleteNeeded = true;
pdf.BindXML(xmlDoc, null);
pdf.IsTruetypeFontMapCached = false;
return pdf;
}