02 — Import

Change a PDF you already have.

An imported PDF comes back as the same objects you would have built yourself — pages, fonts, images, text. Which means modifying a document is the same work as making one, using the same API you already read on the last page.

09

Import & modify

Import a whole file, or name the pages you want and leave the rest on disk. Then stamp it, annotate it, add pages, reorder them, and write it back out.

Working from a stream rather than a path — an upload, an S3 object, a queue payload? Pdf::importRawData() takes the bytes.

Importing in the docs →
stamp.php
use Pop\Pdf\Pdf;
use Pop\Pdf\Document\Font;
use Pop\Pdf\Document\Page\Text;

// the whole file
$doc = Pdf::importFromFile('contract.pdf');

// or only the pages you need
$doc = Pdf::importFromFile(
    'contract.pdf', pages: [2, 4, 6]
);

// register the font you stamp with
$doc->addFont(Font::ARIAL_BOLD);

$doc->getPage(1)->addText(
    new Text('DRAFT', size: 48),
    Font::ARIAL_BOLD, x: 180, y: 400
);

Pdf::writeToFile($doc, 'contract-draft.pdf');
10

Merge PDFs

Combine files in order, into one document object you can keep working on — add a cover page, number the result, stamp it — before you write it.

Same story for streams: Pdf::mergeRawData().

Merging in the docs →
merge.php
use Pop\Pdf\Pdf;

$doc = Pdf::merge([
    'cover.pdf',
    'body.pdf',
    'appendix.pdf',
]);

Pdf::writeToFile($doc, 'report.pdf');
11

Open a protected PDF

An encrypted source opens with its password and is transparent from there — the document you get back is the same object as any other, with no memory of having been locked. Merging takes one password per source, so a protected file can be combined with plain ones.

Either password works to open it. The Standard Security Handler only distinguishes the two when deciding which permissions apply afterwards.

Writing an imported document back out drops the encryption unless you call setSecurity() again — and on an imported document that call does not yet reach literal strings carried over from the source, such as an annotation URL.

Protected PDFs in the docs →
unlock.php
use Pop\Pdf\Pdf;

// either password opens the document
$doc = Pdf::importFromFile(
    'statement.pdf', password: 'open-me'
);

// merging: key each password by its index
$doc = Pdf::merge([
    'cover.pdf',
    'statement.pdf',
], passwords: [1 => 'open-me']);

Pdf::writeToFile($doc, 'combined.pdf');
12

Build a PDF from images

Hand it an array of images and each one becomes a page. Useful for turning a batch of scans, screenshots or camera photos into a single document.

This is the exact inverse of extracting pages as images — the same library does the round trip.

Images to PDF in the docs →
from-images.php
use Pop\Pdf\Pdf;

$images = [
    'scans/page-01.jpg',
    'scans/page-02.jpg',
];

// one page per image
$doc = Pdf::importFromImages($images);

Pdf::writeToFile($doc, 'scanned-batch.pdf');