As I explain in my Essay on pagination, the default SAS pagination and page numbering is rarely sufficient for materials intended for publication. Manual intervention is almost always required.
Before ODS, the conventional approach was to count characters and work out where page breaks occurred. Tedious but straightforward. If "Page <x> of <y>" was required, the usual solution was to make two passes of the file: the first time a marker was written where the page number was required (and the number of pages calculated), the second replaced the marker with the actual text required.
Although ODS allows us to use proportional fonts (which makes working out where page breaks are required harder), it has a couple of neat tricks that makes getting the actual page numbering correct much simpler.
An RTF document can contain fields, two of which are the current page number and the number of pages in the document. So all we need to do is put these fields where we want the page numbers to appear, and the job's done. No need to count pages or pass through the data twice.
To get an RTF field in to the document, we need to pass RTF code from ODS to the document. If you're using SAS Version 8, you need to set PROTECTSPECIALCHARS to OFF for the style element that renders the location where our page numbers will appear. SAS 9 has a neater way to handle footnotes, which I'll come to in a moment.
I'll assume that you want to put your page numbers in a FOOTNOTE. FOOTNOTEs are rendered by the SystemFooter style element. So we start by redefining the default RTF style:
PROC TEMPLATE;
STYLE MyRTF FROM styles.RTF/STORE=WORK.Templates;
STYLE SystemFooter FROM SystemFooter/
PROTECTSPECIALCHARS=OFF;
END;
RUN;
Now we make the new style available:
ODS PATH (PREPEND) WORK.Templates;
To include the page number, cut and paste the following text into your SAS code:
{Page {\field{\*\fldinst PAGE}}
and for the number of pages, cut and paste this:
{\field{\*\fldinst NUMPAGES}}
Finally, when opening the RTF file, use a statement like this:
ODS RTF FILE=<my-RTF-file-spec> STYLE=MyRTF;
It's messy, but it works in both SAS Version 8 and SAS 9. Here's some example code and output.
In version 9, the inline formatting commands {thispage}, {numpages} and {pageof} provide a much neater solution. Click here for details.
Note that whichever solution you adopt, the page numbers are inserted as fields. This means that they may appear incorrect when you first open the document. (However, they will always print correctly.) You need to update them to see the correct values on the screen. On Windows, you can hit <CTRL/A><F9> to do this. Also, if you then link the file into a larger document, the page numbering may go astray. as the NUMPAGES field refers to the entire document, not just the one you've linked.
This technique will work with any Word or RTF field, not just page numbering fields.