HTML JPG PDF XML DOCX
  Product Family
PDF

Extract Attachments from PDF in PHP SDK

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

Get Started

How to extract attachments from 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 extract attachments using PHP SDK

Aspose.PDF Cloud PHP developers can easily extract 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. Perform the extracting attachment actions for PDF document
  5. Downloads each attachment and saves it locally
 

This sample code shows extracting all attachments of 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);

    $localPath = "../Samples/";
    $localFileName = "../Samples/Attachments/sample_attachment.pdf";
    $storageFileName = "sample_attachment.pdf";

    try {
        $pdfApi->uploadFile($storageFileName, $localFileName);

        $result = $pdfApi->getDocumentAttachments($storageFileName);

        if ($result->getCode() == 200 && $result->getAttachments()) {
            if (empty($result->getAttachments()->getList())) {
                echo "Unexpected error: No attachments to download.\n";
                return;
            }

            foreach ($result->getAttachments()->getList() as $index => $attachment) {
                try {
                    $response = $pdfApi->getDocumentAttachmentByIndex($storageFileName, $index);
                    $filePath = $localPath . $response->getAttachment()->getName();
                    file_put_contents($filePath, json_encode($response));
                } catch (Exception $e) {
                    echo "Failed to download attachment {$index}: {$e->getMessage()}\n";
                    return;
                }
            }
        } else {
            echo "Failed to retrieve attachments.\n";
            return;
        }
    } catch (Exception $e) {
        echo "Error processing PDF attachments: {$e->getMessage()}\n";
        return;
    }