Cesar
Cesar

Reputation: 4116

Embedd (not concat) multiple pdf into one (using php)

Is it possible to embedd a pdf file into another using php? If not php, can this be made using another open source software?

The use case is the following:

I have a template.pdf file with empty spots which should be filled dynamically with another pdf files.

Example:

I have a pdf file with four empty slots, the firts three should be filled with the contents of pdf files: a.pdf, b.pdf, c.pdf and the last one should be filled with text dinamically created.

template.pdf

+-----------------------+-------+-------+
|         a.pdf         | b.pdf | c.pdf |
+-----------------------+-------+-------+
|        embedded dynamic text          |
+---------------------------------------+

Upvotes: 1

Views: 177

Answers (1)

Cesar
Cesar

Reputation: 4116

I was able to fulfill my requirements using tcpdf.php and fpdi.php.

It's not the most beautiful code, but It's working.

<?php

require_once dirname(__FILE__) . '/pdf-lib/tcpdf/tcpdf.php';
require_once dirname(__FILE__) . '/pdf-lib/fpdi/fpdi.php';


$my_base_path = dirname(__FILE__);


$pdf = new FPDI('P', 'mm', 'LETTER', true, 'UTF-8', false, true);


//following is the style pf the boxes
$style = array('width' => 0.3, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0,  'color' => array(0, 0, 0));

/*
 * Set the template file
 */
$pdf->setSourceFile($my_base_path . '/template.pdf');
$tplidx = $pdf->ImportPage(1);
$pdf->addPage();
$pdf->useTemplate($tplidx);

/*
 * Set file1.pdf
 * Width of a.pdf + b.pdf
 */
$pdf->setSourceFile($my_base_path . '/file1.pdf');
$pdf->setPage(1);
$tplidx = $pdf->ImportPage(1);
$size = $pdf->useTemplate($tplidx, 12.4, 25.90, 124);
$pdf->Cell(12.4, 26.67);
$pdf->Rect(80.29, 62.147, 55.919, 62.815, 'D', $style);// box around the ballot

/*
 * Set file2.pdf
 * Width of c.pdf
 */
$pdf->setSourceFile($my_base_path . '/file2.pdf');
$pdf->setPage(1);
$tplidx = $pdf->ImportPage(1);
$size = $pdf->useTemplate($tplidx, 147.29, 26.67, 56.0);
$pdf->Cell(147.29, 26.67);
$pdf->Rect(147.349, 62.147, 55.919, 62.815, 'D', $style);// box around the ballot



/*
 * Set embedded dynamic text
 */

$text = 'embedded dynamic text';

$pdf->setPage(1);
$pdf->setXY(12.6, 147.24);

//$pdf->Cell(0, 0, $text_nombre, 0, 0, 'C');
$pdf->writeHTMLCell(0, 0, 12.6, 147.24, $text, 0, 0, 0, true, 'C');


$pdf->Output('out.pdf', 'I');
exit;
?>

Upvotes: 1

Related Questions