We generate a word & PDF document using Aspose.Words in C#.
This word document have multiple headings and of font family Georgia. When we add TOC to the document, TOC is by default inheriting the font family of actual Headers though we set Helvetica as font family for the current paragraph.
To solve this issue we tried writing following code:
// Calling code
ApplyStyles(builder, paragraphStyle, StyleIdentifier.Toc1);
ApplyStyles(builder, paragraphStyle, StyleIdentifier.Toc2);
ApplyStyles(builder, paragraphStyle, StyleIdentifier.Toc3);
builder.InsertTableOfContents("\\o \"2-2\" \\h \\z \\u");
private static void ApplyStyles(DocumentBuilder builder, Styles paragraphStyle, StyleIdentifier styleIdentifyer)
{
var style = builder.Document.Styles[styleIdentifyer];
style.Font.Name = paragraphStyle.FontFamily; // Setting this as Helvetica
style.Font.Size = paragraphStyle.FontSize;
var paragraphFormat = style.ParagraphFormat;
paragraphFormat.SpaceBefore = paragraphStyle.SpaceBefore;
paragraphFormat.LineSpacing = paragraphStyle.LineHeight;
paragraphFormat.LineSpacingRule = LineSpacingRule.Exactly;
var pageSetup = builder.PageSetup;
var margins = 25;
var tabStopPosition = pageSetup.PageWidth - (pageSetup.LeftMargin + pageSetup.RightMargin) - margins;
paragraphFormat.LeftIndent += margins;
paragraphFormat.TabStops.Add(new TabStop(tabStopPosition, TabAlignment.Right, TabLeader.Dots));
}
Though we set the font family as Helvetica, it is not getting applied for TOC. Hence we have written following workaround to apply the font family:
document.UpdateFields();
SetTOCFontStyles(builder);
private void SetTOCFontStyles(Document document)
{
var tocFields = document.Range.Fields.OfType<FieldToc>();
foreach (var tocEntry in tocFields)
{
var fontName = tocEntry.Start.Font.Name;
var runs = tocEntry.Start.ParentParagraph.ParentNode.GetChildNodes(NodeType.Run, true);
foreach (Run title in runs)
{
if (!title.ParentParagraph.ParagraphFormat.IsHeading)
{
title.Font.Name = fontName;
}
}
}
}
This code is applying the font family as expected when the document is exported as word document. But while same document is exported in PDF format, changes are not being applied for font family. But all other styles are reflecting properly.
Can you provide any suggestions on how can we fix this issue?