如何在 Aspose.Words 中插入自定义页码

How to insert custom page number in Aspose.Words

我想使用 Aspose.Words 向 word 文档添加自定义页码(如 1/2、2/2)。但是我找不到任何 c# 语言的示例。我试图覆盖页脚,但我无法为页码指定格式。 请帮助! 谢谢!


编辑


在我尝试第一个答案后,它按我想要的方式工作,但又出现了另一个问题。我将子文档添加到主文档。我只能格式化主文档的编号。子文件仍然有普通的页码。 这里有一个代码示例;

   public void AddChildDocs (System.IO.Stream parentStream, List<System.IO.Stream> childStreams)
    {

        doc = new Aspose.Words.Document(parentStream);

        if (Items.Count > 0)
        {
            WordReplacer evaluator = new WordReplacer(this);
            doc.Range.Replace(new Regex(ReplaceRegex), evaluator, false);
        }
        foreach (var item in childStreams)
        {
            Aspose.Words.Document childDoc = new Aspose.Words.Document(item);
            if (Items.Count > 0)
            {
                WordReplacer evaluator = new WordReplacer(this);
                childDoc.Range.Replace(new Regex(ReplaceRegex), evaluator, false);
            }
            doc.AppendDocument(childDoc, ImportFormatMode.KeepSourceFormatting);
        }

        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
        builder.InsertField("PAGE", "");
        builder.Write(" / ");
        builder.InsertField("NUMPAGES", "");
    }

您可以从 Aspose 文档中的 this page 中获得灵感。以下是取自同一页面的示例代码,但仅与自定义页码相关。

String src = dataDir + "Page numbers.docx";
String dst = dataDir + "Page numbers_out.docx";

// Create a new document or load from disk
Aspose.Words.Document doc = new Aspose.Words.Document(src);
// Create a document builder
Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc);
// Go to the primary footer
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// Add fields for current page number
builder.InsertField("PAGE", "");
// Add any custom text
builder.Write(" / ");
// Add field for total page numbers in document
builder.InsertField("NUMPAGES", "");

// Import new document
Aspose.Words.Document newDoc = new Aspose.Words.Document(dataDir + "new.docx");
// Link the header/footer of first section to previous document
newDoc.FirstSection.HeadersFooters.LinkToPrevious(true);
doc.AppendDocument(newDoc, ImportFormatMode.UseDestinationStyles);
// Save the document
doc.Save(dst);

我在 Aspose 工作,担任开发人员推广员。

这是在 aspose.word 中设置自定义页码的代码,当您设置页边距和起始页码时,它会在该特定页面区域完成时自动获取下一页。试试这个它会起作用...

section.PageSetup.PaperSize = PaperSize.Letter;
section.PageSetup.LeftMargin = 10;
section.PageSetup.RightMargin = 10;
section.PageSetup.TopMargin = 00;
section.PageSetup.BottomMargin = 0;
section.PageSetup.HeaderDistance = 50;
section.PageSetup.FooterDistance = 50;
section.PageSetup.Borders.Color = Color.Black;
section.PageSetup.PageStartingNumber = 1;