Skip to content

Add "Merger > Various > Split Memory Optimized" demo #26

Description

@JanSlabon

We should add a demo, that uses a split process encapsualted in a function scope to use less memory.

/**
 * @param string $path Path of the file you want to split
 * @param callable $name A callable, that returns a path for the resulting page
 * @param int $limit Numbers of pages that should be split by an initiated document instance
 * @return void
 */
function split(string $path, callable $name, int $limit = 100)
{
    $pageNo = 1;
    $split = static function(string $path) use ($limit, $name, &$pageNo) {
        $document = \setasign\SetaPDF2\Core\Document::loadByFilename($path);
        $pageCount = $document->getCatalog()->getPages()->count();
        $document->getCatalog()->getPages()->ensureAllPageObjects();

        for (; $pageNo <= $pageCount && $limit > 0; $pageNo++) {
            $merger = new \setasign\SetaPDF2\Merger\Merger();
            $merger->addDocument($document, $pageNo);
            $merger->merge();
            $resDocument = $merger->getDocument();
            $resDocument->setWriter(new \setasign\SetaPDF2\Core\Writer\FileWriter($name($pageNo, $pageCount, $path)));
            $resDocument->save()->finish();
            $limit--;
        }

        unset($resDocument, $merger, $document);
        gc_collect_cycles();

        return $pageCount - $pageNo;
    };

    while ($split($path) > 0) {
        echo memory_get_usage(true) . PHP_EOL; // debug
    }
}

split($_GET['f'], static function (int $pageNo, int $pageCount, string $path) {
    return '_split/'. $pageNo . '.pdf';
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions