Add Page Number to PDF

Contents
[ ]

All the documents must have page numbers in it. The page number makes it easier for the reader to locate different parts of the document. Aspose.PDF for PHP via Java allows you to add page numbers with PageNumberStamp.

You can use PageNumberStamp class to add a page number stamp in a PDF document. The PageNumberStamp class provides methods to create a page number-based stamp like format, margins, alignments, starting number, etc. To add a page number stamp, you need to make a Document object and a PageNumberStamp object with required text properties. After that, you can call addStamp(..) method of the Page class to add the stamp in PDF file. You can also set the font attributes of the page number stamp.

The following code snippet shows you how to add page numbers in a PDF file.


    // Open document
    $document = new Document($inputFile);

    // Create page number stamp
    $pageNumberStamp = new PageNumberStamp();

    // Whether the stamp is background
    $Center = (new HorizontalAlignment())->getCenter();
    $pageNumberStamp->setBackground(false);
    $pageNumberStamp->setFormat("Page # of " . $document->getPages()->size());
    $pageNumberStamp->setBottomMargin(10);
    $pageNumberStamp->setHorizontalAlignment($Center);
    $pageNumberStamp->setStartingNumber(1);

    $fontRepository = new FontRepository();
    // Set text properties
    $pageNumberStamp->getTextState()->setFont($fontRepository->findFont("Arial"));
    $pageNumberStamp->getTextState()->setFontSize(14.0);
    $pageNumberStamp->getTextState()->setFontStyle(FontStyles::$Bold);
    $pageNumberStamp->getTextState()->setForegroundColor((new Color())->getAqua());

    // Add stamp to particular page
    $document->getPages()->get_Item(1)->addStamp($pageNumberStamp);

    // Save output document
    $document->save($outputFile);
    $document->close();