Add Attachments to PDF via PHP

How to Add Attachments in PDF programmatically with PHP

How to Manage Attachments Using PHP via Java Library

In order to add Attachments in PDF file, we’ll use Aspose.PDF API which is a feature-rich, powerful and easy to use document manipulation API for php-java platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Add Attachments in PDF File via PHP


You need Aspose.PDF library to try the code in your environment.

  1. Create a new PHP project.
  2. Add a reference to Aspose.PDF DLL.
  3. Create a Document object.
  4. Create a FileSpecification object with the file you are adding, and file description.
  5. Add the FileSpecification object to the Document object’s EmbeddedFiles collection, with the collection’s Add method
  6. Save the PDF file.

Adding Attachment to PDF document


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

// Set up a new file to be added as attachment
$fileSpecification = new FileSpecification("sample.txt", "Sample text file");
// Add an attachment to document's attachment collection
$document->getEmbeddedFiles()->add($fileSpecification);

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