How to insert a field into the header

The following code inserts a centred page number field as the header on each page.

  1. Call CHeaderFooter::CreateTextL() to allocate and construct the rich text component which is owned by the header/footer.

  2. Retrieve the rich text component by calling CHeaderFooter::Text(). This can be used to apply rich text formatting to the header and footer.

  3. Construct a paragraph format container and mask using CParaFormat and TParaFormatMask to apply paragraph formatting to the header. The centre alignment attribute is set in the container.

  4. Use CRichText::ApplyParaFormatL() to apply the formatting to the header.

  5. To create a field in a header, use CRichText::NewTextFieldL(), specifying the UID of the desired field type. Update the field before printing it.

// Set header text
_LIT(KPage,"Page  "); // Header text
TBuf<8> buf(KPage); 
CTextField* field=iPrintSetup->Header()->Text()->NewTextFieldL(KPageNumberFieldUid);
// Make field at doc pos'n 5 visible

// Centre the paragraph containing header
CParaFormat* paraFormat=CParaFormat::NewL();
TParaFormatMask paraFormatMask;
paraFormatMask.SetAttrib(EAttAlignment); // To centre align text
delete paraFormat;


  • To insert any field type other than the page number into a document, a field factory is required.