Add Text to PDF using PHP

Add text to PDF document with PHP via Java. Use Aspose.PDF to modify PDF documents programmatically

How to Work with Text in PDF using PHP via Java Library

To add Text into PDF File, we’ll use Aspose.PDF for PHP via Java API which is a feature-rich, powerful and easy-to-use document manipulation tool in php-java. Install Tomcat 9.0 version on any location, add Aspose.PDF.war, for more details check the GitHub page.

Add Text to PDF File via PHP


You need Aspose.PDF for PHP via Java to try the code in your environment.

  1. Load the PDF with an instance of Document.
  2. Create a TextParagraph and define its properties.
  3. Add the TextParagraph to Page using TextBuilder.
  4. Save the file again.

Add Text to PDF - PHP

This sample code shows how to add text into PDF document - PHP


    // 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();