In that answer I see that using FPDI you are able to fill parts of a PDF. Based on that I make my own class that fills a pdf with values on specific positions:
use FPDI;
class PDFFiller
{
/**
* @param array $fields Array of field positions
* @param array $values Array of fiels values
*
* $fields format:
* 'field_name'=>[
* 'page' => int // The page where field is located
* 'x' => int // X position
* 'y' => int // Y position
* ]
*
* $values => ['field_name' => $value]
*/
function __construct(array $fields, array$values)
{
$this->fields = $fields;
$this->values = $values;
}
public function fill($in_file,$out_file): string
{
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile($in_file);
// import page 1
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page
foreach($fields as $field => $value){
$tplIdx = $pdf->importPage($value['page']);
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
$this->pdf->SetFont('Arial', '', '13');
$this->pdf->SetTextColor(0,0,0);
$this->pdf->SetXY($field['x'], $field['y']);
$this->pdf->Write(0, $values[$field]);
}
$this->pdf->Output($out_file, 'D');
}
}
And I want to test it. The scenario I want to test is that once I fill a pdf file the generated pdf file contains the appropriate values on the appropriate positions that I configured it via $fields
constructor parameter.
The only think that I found so far is to assert that a specific document has specific amount of pages:
$fields = [
'myfield' => [ 'page' => 1, 'x'=>2,'y'=>3]
];
$values = [ 'myfield' => 'Lorem Ipsum' ]
$expectedPages = 2;
$filler = new PDFFiller($fields,$values);
$filler->fill('input.pdf','output.pdf')
$pdf = new FPDI();
$pagesNum = $pdf->setSourceFile('input.pdf');
$this->assertEquals($expectedPages,$pagesNum);
How can I do this?