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
iPrintSetup->Header()->CreateTextL();
_LIT(KPage,"Page  "); // Header text
TBuf<8> buf(KPage); 
iPrintSetup->Header()->Text()->InsertL(0,buf);
CTextField* field=iPrintSetup->Header()->Text()->NewTextFieldL(KPageNumberFieldUid);
iPrintSetup->iHeader->iText->InsertFieldL
(5,field,KPageNumberFieldUid); 
// Make field at doc pos'n 5 visible
iPrintSetup->Header()->Text()->UpdateFieldL(5); 

// Centre the paragraph containing header
CParaFormat* paraFormat=CParaFormat::NewL();
TParaFormatMask paraFormatMask;
paraFormat->iHorizontalAlignment=CParaFormat::ECenterAlign;
paraFormatMask.SetAttrib(EAttAlignment); // To centre align text
iPrintSetup->Header()->Text()->ApplyParaFormatL(paraFormat,paraFormatMask,0,1); 
delete paraFormat;

Note

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