Add Text to PDF file

Contents
[ ]

To add text to existing PDF file:

  1. Open the input PDF using the Document object.
  2. Get the particular page to which you want to add the text.
  3. Create a text fragment with the content “Aspose.PDF”.
  4. Set the position of the text fragment on the page.
  5. Set the text properties of the text fragment.
  6. Create a TextBuilder object for the page.
  7. Append the text fragment to the PDF page.
  8. Save the resulting PDF document to the output file.

Adding Text

The following code snippet shows you how to add text in an existing PDF file.


    // Open document
    $document = new Document($inputFile);
    
    // get particular page
    $page = $document->getPages()->add();
    
    // create text fragment
    $textFragment = new TextFragment("Aspose.PDF");
    $textFragment->setPosition(new Position(80, 700));

    // set text properties
    $fontRepository = new FontRepository();
    
    $colors = new Color();
    $textFragment->getTextState()->setFont($fontRepository->findFont("Verdana"));
    $textFragment->getTextState()->setFontSize(14);
    $textFragment->getTextState()->setForegroundColor($colors->getBlue());
    $textFragment->getTextState()->setBackgroundColor($colors->getLightGray());

    // create TextBuilder object
    $textBuilder = new TextBuilder($page);
    // append the text fragment to the PDF page
    $textBuilder->appendText($textFragment);

    // Save resulting PDF document.    
    $document->save($outputFile);
    $document->close();