HTML JPG PDF XML DOCX
  Product Family
PDF

Add Attachments to PDF in PHP SDK

API for adding attachments in PDF documents with Aspose.PDF Cloud PHP SDK

Get Started

How to append attachments in PDF documents using Cloud PHP SDK

For working with attachments in PDF documents, we’ll use Aspose.PDF Cloud PHP SDK This Cloud SDK SDK assists PHP programmers in developing cloud-based PDF creator, annotator, editor, and converter apps using PHP programming language via Aspose.PDF REST API. Open NPM package manager, search for Aspose.PDF Cloud, and install.

Steps to add attachments using PHP SDK

Aspose.PDF Cloud PHP developers can easily append attachments in PDF documents. Developers need just a few lines of code.

  1. Loads API credentials from a JSON file
  2. Configures the API client using the loaded credentials
  3. Uploads a local PDF file to the Aspose storage
  4. Append file as attachments
  5. Downloads and save the PDF
 

This sample code shows append file attachment to PDF document using PDF Cloud PHP SDK


    <?php

    require_once 'vendor/autoload.php';

    use Aspose\PDF\Api\PdfApi;
    use Aspose\PDF\Configuration;
    use Aspose\PDF\Model\AttachmentInfo;
    use Aspose\PDF\Model\AttachmentResponse;

    // Load credentials
    $credentials = json_decode(file_get_contents("./credentials.json"), true);
    $apiKey = $credentials["key"];
    $appSID = $credentials["id"];

    $config = new Configuration();
    $config->setAppKey($apiKey);
    $config->setAppSid($appSID);

    $pdfApi = new PdfApi(null, $config);

    $localFileName = "../Samples/Attachments/sample_attachment.pdf";
    $storageFileName = "sample_attachment.pdf";
    $localAttachmentFileName = "../Samples/Attachments/file_example_MP3_700KB.mp3";
    $storageAttachmentFileName = "file_example_MP3_700KB.mp3";
    $resultFileName = "../Samples/Attachments/sample_attachment.pdf";

    try {
        $pdfApi->uploadFile($storageFileName, $localFileName);
        echo "Uploaded: " . $storageFileName . "\n";

        $pdfApi->uploadFile($storageAttachmentFileName, $localAttachmentFileName);
        echo "Uploaded: " . $storageAttachmentFileName . "\n";

        $attachment = new AttachmentInfo([
            'name' => $storageAttachmentFileName,
            'path' => $storageAttachmentFileName,
            'description' => "An example of MP3 file",
            'mime_type' => "audio/mpeg"
        ]);

        $appendResult = $pdfApi->postAddDocumentAttachment($storageFileName, $attachment);

        if ($appendResult->getCode() == 200) {
            echo "Status: " . $appendResult->getStatus() . "\n";
            $downloadResult = $pdfApi->downloadFile($storageFileName);
            file_put_contents($resultFileName, $downloadResult);
        } else {
            echo "Unexpected error: can't download attachments.\n";
            return;
        }
    } catch (Exception $e) {
        echo "Error adding attachment: {$e->getMessage()}\n";
        return;
    }