用 Delphi 在Word中创建页码X/Y

hsvhsicv  于 2023-01-02  发布在  其他
关注(0)|答案(2)|浏览(166)

我想在通过 Delphi 生成的Word文件中添加一个Y编号的X页,该文件为:- 不大胆;- 字体大小为8;- 右对齐。
注:Y为总页数; X是页码的索引。
到目前为止我发现了这个:

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);

我可以更改编号的格式:
文档.节.项目(1).页脚.项目(wdHeaderFooterPrimary).页码.页码样式:= wdPageNumberStyleLowercaseRoman;
但是没有Y格式的第X页的选项,我该如何实现呢?

azpvetkf

azpvetkf1#

虽然没有具有此格式的可选页眉页码样式,但您可以通过向页眉(或页脚)或其他地方添加特定的MS Word文档字段(PAGE和NUMPAGES字段)来实现此目的。

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;

我把设置字体大小和右对齐作为练习留给读者,因为SO不应该是代码编写服务;=)

huus2vyu

huus2vyu2#

我发现你的代码非常有用,谢谢MartynA.这里是我的版本(有点简化)〉〉

WordApp := CreateOleObject('Word.Application'); // Create a Word Instance
  WordApp.Visible := True; 
  MyDoc := WordApp.Documents.Add;  // Add a new Doc
  MyDoc.ActiveWindow.ActivePane.View.SeekView := 10; // Footer Selected
  WordApp.Selection.TypeText('Page: ');  // Add text to footer
  WordApp.Selection.Fields.Add(WordApp.Selection.Range, 33); // Add Page Counter field to footer
  WordApp.Selection.TypeText(' of ');  // Add text to footer
  WordApp.Selection.Fields.Add(WordApp.Selection.Range, 26); // Add Page Number field to footer
  MyDoc.ActiveWindow.ActivePane.View.SeekView := 0; // Main Doc Selected
  ....

相关问题