Control Pages To Merge The component offers various ways to control which pages should be merged

Introduction

The addFile() and addDocument() methods accept a definition of which pages should be imported in their $pages parameter.

This parameter is very dynamic and can handle various parameter types. 

The $pages Parameter

The component will check a pages parameter internally with the SetaPDF_Merger::_checkPageNumber() method. The initial $pages parameter will be used as the $condition parameter:

Description
protected SetaPDF_Merger::_checkPageNumber (
integer $pageNumber [, null|integer|string|array|callback $condition = null ]
): boolean

Checks a page number against a condition.

Parameters
$pageNumber : integer

The page number

$condition : null|integer|string|array|callback

Valid conditions are:

  • PAGES_XXX constant or null (equal to SetaPDF_Merger::PAGES_ALL)
  • Integer with the valid page number
  • String with the valid page number or the valid range (e.g. '10-12')
  • Array with all valid page numbers
  • Callback with the arguments (int $pageNumber, SetaPDF_Core_Document $document)

The possible constants are defined as following: 

public const string SetaPDF_Merger::PAGES_ALL = 'all'

Keyword for all pages

public const string SetaPDF_Merger::PAGES_FIRST = 'first'

Keyword for the first page

public const string SetaPDF_Merger::PAGES_LAST = 'last'

Keyword for the last page

Examples

 Some examples with the predefined constants: 

PHP
// Let's merge all pages (default behavior):
$merger->addDocument($document, \SetaPDF_Merger::PAGES_ALL);

// Let's merge only the first page:
$merger->addDocument($document, \SetaPDF_Merger::PAGES_FIRST);

// Let's merge only the last page:
$merger->addDocument($document, \SetaPDF_Merger::PAGES_LAST);

Other examples with numeric values and ranges: 

PHP
// Let's merge only page number 2:
$merger->addDocument($document, 2);

// Let's merge page number 2, 3, 4:
$merger->addDocument($document, array(2, 3, 4));

// Let's merge all pages but the first one:
$merger->addDocument($document, '2-');

// Let's merge the first 5 pages:
$merger->addDocument($document, '1-5');

It is also possible to control the behavior by a callback

PHP
// We use an anonymous function here (requires PHP 5.3)
$even = function($pageNumber, $currentDocument) {
    return ($pageNumber % 2) == 0;
};

$merger->addDocument($document, $even);

To change the page order of an existing document, just use the $pages parameter to define the new order. A single document instance or path can be passed several times: 

PHP
$path = 'path/to/document.pdf';
$merger->addFile($path, '11-'); // all pages after page 10
$merger->addFile($path, '1-10'); // the first 10 pages