C# Aspose.Words通过DocumentBuilder添加段落不会更新文档信息

C# Aspose.Words通过DocumentBuilder添加段落不会更新文档信息,c#,aspose,aspose.words,C#,Aspose,Aspose.words,我正在尝试为Aspose的DocumentBuilder类编写一个扩展方法,该方法允许您检查在文档中插入大量段落是否会导致分页符,我希望这会非常简单,但事实证明并非如此: public static bool WillPageBreakAfter(this DocumentBuilder builder, int numParagraphs) { // Get current number of pages int pageCountBefore = builder.Docum

我正在尝试为Aspose的DocumentBuilder类编写一个扩展方法,该方法允许您检查在文档中插入大量段落是否会导致分页符,我希望这会非常简单,但事实证明并非如此:

public static bool WillPageBreakAfter(this DocumentBuilder builder, int numParagraphs) 
{
    // Get current number of pages
    int pageCountBefore = builder.Document.PageCount;

    for (int i = 0; i < numParagraphs; i++) 
    {
        builder.InsertParagraph();
    }

    // Get the number of pages after adding those paragraphs
    int pageCountAfter = builder.Document.PageCount;

    // Delete the paragraphs, we don't need them anymore
    ...

    if (pageCountBefore != pageCountAfter) 
    {
        return true;
    } 
    else  
    {
        return false;
    }
} 
并希望在保存文档时看到0-9写入文档,但实际上不是这样。扩展方法中的writeln似乎没有任何作用

更新2


无论出于什么原因,在访问页面计数后,我都无法使用DocumentBuilder编写任何内容。因此在int pageCountBefore=builder.Document.PageCount之前调用Writeln之类的函数;这行代码行得通,但在这行代码之后再写也没用。

看来我已经明白了

从Aspose文档:

这里最重要的一行是:

这将调用页面布局

调用页面布局意味着它调用UpdatePageLayout,其中文档包含以下注释:

但是,如果在呈现后修改文档,然后尝试再次呈现,则-Aspose.Words不会自动更新页面布局。在这种情况下,应该在再次渲染之前调用UpdatePageLayout

因此,基本上,根据我的原始代码,我必须在写入后调用UpdatePageLayout以获得更新的页面计数

//获取当前页数 int pageCountBefore=builder.Document.PageCount

for (int i = 0; i < numParagraphs; i++) 
{
    builder.InsertParagraph();
}
// Update the page layout.
builder.Document.UpdatePageLatout();

// Get the number of pages after adding those paragraphs
int pageCountAfter = builder.Document.PageCount;

Document.PageCount调用页面布局。您正在使用此属性后修改文档。请注意,使用此属性后修改文档时,Aspose.Words不会自动更新页面布局。在这种情况下,应该调用Document.UpdatePageLayout方法

我与Aspose合作,担任开发人员宣传员

// This invokes page layout which builds the document in memory so note that with large documents this 
// property can take time. After invoking this property, any rendering operation e.g rendering to PDF or image 
// will be instantaneous. 
int pageCount = doc.PageCount;
for (int i = 0; i < numParagraphs; i++) 
{
    builder.InsertParagraph();
}
// Update the page layout.
builder.Document.UpdatePageLatout();

// Get the number of pages after adding those paragraphs
int pageCountAfter = builder.Document.PageCount;