Example E096 : import content streams

PDF

Page 1 of E096_import_content_streams.pdf

Source Code

<?php

declare(strict_types=1);

/**
 * E096_import_content_streams.php
 *
 * Imports the pages of a source PDF that is built inline, with page contents
 * stored in different ways: an array of FlateDecode streams split at token
 * boundaries, a stream encoded with a PNG predictor, streams with abbreviated,
 * per-filter and indirect decode parameters, and an array with a stream that
 * cannot be decoded. Each imported page is a single Form XObject content stream,
 * compressed with FlateDecode.
 *
 * @category    Library
 * @package     Pdf
 * @author      Nicola Asuni <info@tecnick.com>
 * @copyright   2002-2026 Nicola Asuni - Tecnick.com LTD
 * @license     https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
 * @link        https://github.com/tecnickcom/tc-lib-pdf
 *
 * This file is part of tc-lib-pdf software library.
 */

// NOTE: local file reads (images, fonts, attachments) are restricted to an allowlist of
// trusted paths that covers this package tree, so run the examples in place. To read assets
// from other locations, list them in the 'allowedPaths' entry of the fileOptions constructor
// parameter (see E047_remote_resources_security.php).

// NOTE: run make fonts in the project root to generate the dependencies and example fonts.

// autoloader when using Composer
require __DIR__ . '/../vendor/autoload.php';

// define fonts directory
\define('K_PATH_FONTS', \realpath(__DIR__ . '/../vendor/tecnickcom/tc-lib-pdf-font/target/fonts'));

// ---- Step 1: build the source PDF ----

/**
 * Returns the body of a stream object with the given dictionary entries.
 */
$stream = static fn(string $dict, string $data): string => (
    '<< /Length ' . \strlen($data) . ' ' . $dict . " >>\nstream\n" . $data . "\nendstream"
);

/**
 * Returns the data Flate-compressed.
 */
$flate = static fn(string $data): string => (string) \gzcompress($data);

/**
 * Returns the data encoded with the PNG Up predictor (/Predictor 12) on rows of
 * $columns bytes, the last row padded with spaces.
 */
$pngUp = static function (string $data, int $columns): string {
    $data = \str_pad($data, (int) \ceil(\strlen($data) / $columns) * $columns, ' ');
    $out = '';
    $prev = \str_repeat("\x00", $columns);
    foreach (\str_split($data, \max(1, $columns)) as $row) {
        $out .= "\x02";
        for ($idx = 0; $idx < $columns; ++$idx) {
            $out .= \chr((\ord($row[$idx]) - \ord($prev[$idx]) + 256) % 256);
        }

        $prev = $row;
    }

    return $out;
};

/**
 * Returns the content of a framed page with a title.
 */
$page = static fn(string $fill, string $stroke, string $title): string => (
    $fill
    . " rg 40 40 340 515 re f\n"
    . $stroke
    . " RG 4 w 40 40 340 515 re S\n0 g BT /F1 16 Tf 60 500 Td ("
    . $title
    . ') Tj ET'
);

$res = '/Resources << /Font << /F1 3 0 R >> >>';
$page1 = $page('0.85 0.90 1', '0 0 0.6', 'Source page 1: /Contents array');
$page2 = $page('1 0.92 0.80', '0.6 0.3 0', 'Source page 2: PNG predictor');
$page3 = $page('0.85 1 0.85', '0 0.5 0', 'Source page 3: decode parameters');
$page4 = $page('1 0.88 0.88', '0.6 0 0', 'Source page 4: undecodable stream');

// Page 1 is split in three streams; the splits fall between operands and operators.
$split1 = \strpos($page1, ' re f');
$split2 = \strpos($page1, '0 g BT');

$columns = 9;
$page3Lines = \explode("\n", $page3);

// A5 pages.
$objects = [
    1 => '<< /Type /Catalog /Pages 2 0 R >>',
    2 => '<< /Type /Pages /Kids [4 0 R 8 0 R 10 0 R 15 0 R] /Count 4 /MediaBox [0 0 420 595] >>',
    3 => '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>',
    // Page 1: /Contents array of three FlateDecode streams.
    4 => '<< /Type /Page /Parent 2 0 R ' . $res . ' /Contents [5 0 R 6 0 R 7 0 R] >>',
    5 => $stream('/Filter /FlateDecode', $flate(\substr($page1, 0, (int) $split1))),
    6 => $stream('/Filter /FlateDecode', $flate(\substr($page1, (int) $split1, (int) $split2 - (int) $split1))),
    7 => $stream('/Filter /FlateDecode', $flate(\substr($page1, (int) $split2))),
    // Page 2: one FlateDecode stream with a PNG predictor.
    8 => '<< /Type /Page /Parent 2 0 R ' . $res . ' /Contents 9 0 R >>',
    9 => $stream(
        '/Filter /FlateDecode /DecodeParms << /Predictor 12 /Columns ' . $columns . ' >>',
        $flate($pngUp($page2, $columns)),
    ),
    // Page 3: /DP abbreviation, a filter chain with per-filter parameters, and
    // an indirect parameter dictionary.
    10 => '<< /Type /Page /Parent 2 0 R ' . $res . ' /Contents [11 0 R 12 0 R 13 0 R] >>',
    11 => $stream(
        '/Filter /FlateDecode /DP << /Predictor 12 /Columns ' . $columns . ' >>',
        $flate($pngUp($page3Lines[0] ?? '', $columns)),
    ),
    12 => $stream(
        '/Filter [/ASCIIHexDecode /FlateDecode] /DecodeParms [null << /Predictor 12 /Columns ' . $columns . ' >>]',
        \bin2hex($flate($pngUp($page3Lines[1] ?? '', $columns))) . '>',
    ),
    13 => $stream('/Filter /FlateDecode /DecodeParms 14 0 R', $flate($pngUp($page3Lines[2] ?? '', $columns))),
    14 => '<< /Predictor 12 /Columns ' . $columns . ' >>',
    // Page 4: the middle stream declares FlateDecode but holds plain bytes.
    15 => '<< /Type /Page /Parent 2 0 R ' . $res . ' /Contents [16 0 R 17 0 R 18 0 R] >>',
    16 => $stream('/Filter /FlateDecode', $flate((string) \strstr($page4, '0 g BT', true))),
    17 => $stream('/Filter /FlateDecode', '0 0 1 rg 0 0 420 595 re f'),
    18 => $stream('/Filter /FlateDecode', $flate((string) \strstr($page4, '0 g BT'))),
];

$sourcePdfData = "%PDF-1.7\n";
$xref = '';
foreach ($objects as $num => $body) {
    $xref .= \sprintf("%010d 00000 n \n", \strlen($sourcePdfData));
    $sourcePdfData .= $num . " 0 obj\n" . $body . "\nendobj\n";
}

$xrefStart = \strlen($sourcePdfData);
$size = \count($objects) + 1;
$sourcePdfData .=
    "xref\n0 "
    . $size
    . "\n0000000000 65535 f \n"
    . $xref
    . "trailer\n<< /Size "
    . $size
    . " /Root 1 0 R >>\nstartxref\n"
    . $xrefStart
    . "\n%%EOF\n";

// ---- Step 2: import every page into a new document ----

$pdf = new \Com\Tecnick\Pdf\Tcpdf();
$pdf->setCreator('tc-lib-pdf');
$pdf->setAuthor('Nicola Asuni');
$pdf->setSubject('tc-lib-pdf example: 096');
$pdf->setTitle('Import Page Content Streams');
$pdf->setKeywords('TCPDF tc-lib-pdf example import content stream FlateDecode predictor DecodeParms');
$pdf->setPDFFilename('096_import_content_streams.pdf');

$sourceId = $pdf->setImportSourceData($sourcePdfData);

$labels = [
    1 => 'Three FlateDecode streams, split between operands and operators. Expected: blue frame and title.',
    2 => 'One FlateDecode stream with /DecodeParms << /Predictor 12 >>. Expected: orange frame and title.',
    3 =>
        'Streams with /DP, [/ASCIIHexDecode /FlateDecode] with [null << ... >>] parameters,'
            . ' and an indirect /DecodeParms. Expected: green frame and title.',
    4 =>
        'The middle stream cannot be decoded and is left out with a warning.'
            . ' Expected: red frame and title, no blue page fill.',
];

foreach ($labels as $pageNum => $label) {
    $pdf->addPageFromImport($sourceId, $pageNum);
    $font = $pdf->font->insert($pdf->pon, 'helvetica', 'B', 11);
    $pdf->page->addContent($font['out']);
    $pdf->addTextCell(txt: $label, posx: 25, posy: 40, width: 98, drawcell: false);
}

$font = $pdf->font->insert($pdf->pon, 'helvetica', '', 9);
$pdf->page->addContent($font['out']);
// The import warnings are part of getWarnings() once the document is output.
$pdf->addTextCell(
    txt: 'Expected warning: "The imported page 4 has 1 content stream(s) that cannot be decoded: they are left out".',
    posx: 25,
    posy: 120,
    width: 98,
    drawcell: false,
);
$pdf->addTextCell(
    txt: 'Each imported page is a Form XObject with one content stream compressed with FlateDecode,'
    . ' whatever the source storage: the output stays close to the source size.',
    posx: 25,
    posy: 160,
    width: 98,
    drawcell: false,
);

// ----------

$rawpdf = $pdf->getOutPDFString();
$pdf->renderPDF(rawpdf: $rawpdf);