Question

I'm looking for a solution to draw a rectangle in an existing pdf file. i try to do this with the function rect(x,y,widht,height) but it doesn't work. I have an error message saying "Function must not be called in 'object' scope'" but i don't understand how correct that.

$searchpath = dirname(dirname(__FILE__)) . '/data';
$pdfinput = "2972172dpi.pdf";
$docoptlist = "requiredmode=minimum";

try {
$p = new PDFlib();
$p->set_option("errorpolicy=return");

# all strings are expected as utf8
$p->set_option("stringformat=utf8");
$p->set_option("SearchPath={{" . $searchpath . "}}");
$doc = $p->open_pdi_document($pdfinput, $docoptlist);
if ($doc == 0) {
    die("Error: " . $p->get_errmsg());
}
$pcosmode = $p->pcos_get_number($doc, "pcosmode");
if ($pcosmode == 0) {
    printf("Minimum mode: no more information available<br/><br/>");
    $p->delete();
    exit(0);
} else {
    $pages = $p->pcos_get_number($doc, "length:pages");
    printf($pages . " pages: <br/>");
    for ($page = 0; $page < $pages; $page++) {
        $param = "pages[" . $page . "]/";
        $widht = round($p->pcos_get_number($doc, $param . "width") / 2.8346456692913);
        $height = round($p->pcos_get_number($doc, $param . "height") / 2.83464566929134);
        printf("Page " . ($page + 1) . " : largeur= %d mm - hauteur= %d mm<br/>", $widht, $height);
        if ($widht == 210 && $height == 297) {
          $p->rect(8.503937007874, 8.503937007874, 578.2677165354, 824.8818897638);
          $p->stroke();
          echo 'Dessiné';
          } */
    }
}
$p->close_pdi_document($doc);
} catch (PDFlibException $e) {
die("PDFlib exception occurred in starter_pcos sample:<br/>" .
        "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
        $e->get_errmsg() . "<br/>");
} catch (Exception $e) {
die($e);
}
Was it helpful?

Solution

you forgot to open an output document. When using PDFlib, you always create a new output PDF, and so using $p->begin_document() is necessary.

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

Then you have to open a page, place your page from the input document and then you can add the rectangle.

You find a very similar sample in the PDFlib cookbook: http://www.pdflib.com/pdflib-cookbook/pdf-import/stamp-pages/php-stamp-pages/ where a text stamp is placed on the page. In your case, you should place the rect.

I guess, it's worth to point to the PDFlib Tutorial, chapter 7.3 "Importing PDF Pages with PDI".

OTHER TIPS

To render a rect it is necessary to begin a page.

You have to do something like this: First you begin a new page. Second fit your PDF file in the new page. Third render the rect on the page. At last close the new pdf.

$p->begin_page(page_width, page_height);
$p->fit_image(template, 0.0, 0.0, "");
$p->rect(55,520,400,20);
$p->end_page();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top