PDFlib Cookbook

cookbook

blocks/clone_blocks

Clone Blocks from another document. Use POCA to copy a modified Block.

Download PHP Code  Switch to Java Code  Show Output 

<?php
/*
 * Clone all Blocks from an input document.
 * 
 * Required software: PPS 9
 * Required data: PDF document with Blocks
 */

/* This is where the data files are. Adjust as necessary. */
$searchpath = dirname(__FILE__,3)."/input";

/* By default annotations are also imported. In some cases this
 * requires the Noto fonts for creating annotation appearance streams.
 * We therefore set the searchpath to also point to the font directory.
 */
$fontpath = dirname(__FILE__,3)."/resource/font";

$infile = "businesscard_blocks.pdf";
$title = "Clone PDFlib Blocks";

try {
    $p = new PDFlib();
    
    $p->set_option("searchpath={" . $searchpath . "}");

    $p->set_option("searchpath={" . $fontpath . "}");

    /* This means we must check return values of load_font() etc. */
    $p->set_option("errorpolicy=return");

    if ($p->begin_document("", "") == 0)
        throw new Exception("Error: " . $p->get_errmsg());

    $p->set_info("Creator", "PDFlib Cookbook");
    $p->set_info("Title", $title);

    /* Open a PDF containing Blocks */
    $indoc = $p->open_pdi_document($infile, "");
    if ($indoc == 0)
        throw new Exception("Error: " . $p->get_errmsg());

    /* Loop over all pages of the input document */
    $pagecount = $p->pcos_get_number($indoc, "length:pages");
    for ($pageno = 1; $pageno <= $pagecount; $pageno++)
    {
        
        $page = $p->open_pdi_page($indoc, $pageno, "");
        if ($page == -1)
            throw new Exception("Error: " . $p->get_errmsg());

        /* Page size may be adjusted by fit_pdi_page() */
        $p->begin_page_ext(0, 0, "width=a4.width height=a4.height");

        /* Copy all Blocks from the page */
        if ($p->process_pdi($indoc, 0,
            "action=copyallblocks block={pagenumber=" . $pageno . "}") == 0)
            throw new Exception("Error: " . $p->get_errmsg());

        /* Import the page content itself */
        $p->fit_pdi_page($page, 0, 0, "adjustpage");

        $p->end_page_ext("");
    }


    $p->end_document("");
    $p->close_pdi_document($indoc);
    $buf = $p->get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=clone_blocks.pdf");
    print $buf;

} catch (PDFlibException $e) {
    echo("PDFlib exception occurred:\n".
        "[" . $e->get_errnum() . "] " . $e->get_apiname() .
        ": " . $e->get_errmsg() . "\n");
    exit(1);
} catch (Throwable $e) {
    echo("PHP exception occurred: " . $e->getMessage() . "\n");
    exit(1);
}

$p = 0;

?>