1

I want to add a page X of Y numbering in a word file generated via Delphi which is: - not bold; - in font size 8; - aligned to the right.

Note that: Y is the total number of pages; X is the index of the page number.

So far I've found this:

procedure Print;
var v:olevariant;

v:=CreateOleObject('Word.Application');
v.Documents.Add;
HeaderandFooter;
firstpage:=true;  

procedure HeaderandFooter;
var adoc,:olevariant;
begin
adoc.Sections.Item(1).Headers.Item(wdHeaderFooterPrimary).Range.Font.Size := 8;
adoc.Sections.Item(1).Footers.Item(wdHeaderFooterPrimary).PageNumbers.Add(wdAlignPageNumberRight);

I can change the format of the numbering:
adoc.Sections.Item(1).Footers.Item(wdHeaderFooterPrimary).PageNumbers.NumberStyle := wdPageNumberStyleLowercaseRoman;

But there is no option for page X of Y format. How do I implement that?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Petermch
  • 191
  • 15

1 Answers1

4

Although there is not a selectable header page-numbering style which has this format, you can do this by adding specific MS Word Document Fields, the PAGE and NUMPAGES ones, to the page header (or footer), or elsewhere.

procedure TForm1.MakeDocWithPageNumbers;
var
  MSWord,
  Document : OleVariant;
  AFileName,
  DocText : String;
begin
  MSWord := CreateOleObject('Word.Application');
  MSWord.Visible := True;

  Document := MSWord.Documents.Add;
  DocText := 'Hello Word!';
  MSWord.Selection.TypeText(DocText);

  if MSWord.ActiveWindow.View.SplitSpecial <> wdPaneNone then
      MSWord.ActiveWindow.Panes(2).Close;
  if (MSWord.ActiveWindow.ActivePane.View.Type = wdNormalView) or (MSWord.ActiveWindow.ActivePane.View.Type = wdOutlineView) then
      MSWord.ActiveWindow.ActivePane.View.Type := wdPrintView;

  MSWord.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;
  MSWord.Selection.TypeText( Text:='Page ');

  MSWord.Selection.Fields.Add( Range:= MSWord.Selection.Range, Type:=wdFieldEmpty, 
    Text:= 'PAGE  \* Arabic ', PreserveFormatting:=True);
  MSWord.Selection.TypeText( Text:=' of ');
  MSWord.Selection.Fields.Add( Range:=MSWord.Selection.Range, Type:=wdFieldEmpty,
    Text:= 'NUMPAGES  \* Arabic ', PreserveFormatting:=True);
  MSWord.Selection.GoTo(What:=wdGoToPage, Which:=wdGoToNext, Count:=1);

  AFileName := 'd:\aaad7\officeauto\worddocwithheader.docx';
  Document.SaveAs(AFileName);
  ShowMessage('Paused');
  Document.Close;
end;

I've left setting the font size and right-alignment as exercises for the reader as SO isn't supposed to be a code-writing service ;=)

MartynA
  • 30,454
  • 4
  • 32
  • 73
  • Works like a charm! I right aligned it via: MSWord.Selection.ParagraphFormat.Alignment := wdAlignParagraphRight; – Petermch Jan 08 '16 at 09:44