页面调整后目录问题

问题描述

我有文档并更改页面大小

builder.PageSetup.PageWidth = ConvertUtil.MillimeterToPoint(219.1);
builder.PageSetup.PageHeight = ConvertUtil.MillimeterToPoint(285.7);

文档有目录,但更改大小后放置错误 wrong sized TOC

有什么建议可以放置正常的 TOC 全页宽度吗?

尝试使用不同的文档。同样的问题。

解决方法

TOC 的宽度由 TOC 样式中的制表位定义。因此,在增加页面宽度后,您还相应地增加了 TOC 样式制表位的大小。请看以下代码:

Document doc = new Document(@"C:\Temp\in.docx");
doc.FirstSection.PageSetup.PageWidth = doc.FirstSection.PageSetup.PageWidth + 200;
UpdateTocStyles(doc);
// Update fields to rebuild the TOC.
doc.UpdateFields();
doc.Save(@"C:\Temp\out.docx");

private void UpdateTocStyles(Document doc)
{
    // List of all TOC styles.
    StyleIdentifier[] tocStyles = new StyleIdentifier[]
    {
        StyleIdentifier.Toc1,StyleIdentifier.Toc2,StyleIdentifier.Toc3,StyleIdentifier.Toc4,StyleIdentifier.Toc5,StyleIdentifier.Toc6,StyleIdentifier.Toc7,StyleIdentifier.Toc8,StyleIdentifier.Toc9
    };

    // Calculate width of the page without left and right margins.
    double pageWidth = doc.FirstSection.PageSetup.PageWidth - doc.FirstSection.PageSetup.RightMargin - doc.FirstSection.PageSetup.LeftMargin;
    // Reset tab stops in TOC styles.
    foreach (StyleIdentifier tocStyleIdentifier in tocStyles)
    {
        Style tocStyle = doc.Styles[tocStyleIdentifier];
        tocStyle.ParagraphFormat.TabStops.Clear();
        tocStyle.ParagraphFormat.TabStops.Add(new TabStop(pageWidth,TabAlignment.Right,TabLeader.Dots));
    }

}