0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
  • This is not possible with FPDI or PHPUnit alone. In the FPDI package we render the expected and current result as a images and compare them then (tests can be found [here](https://github.com/Setasign/FPDI/tree/master/tests/visual)). Maybee that's an option for you, too. – Jan Slabon Nov 23 '20 at 18:20
  • So in order to test it I will hafta to use the normal Dependency Injection and mocks. – Dimitrios Desyllas Nov 24 '20 at 08:18
  • What do you want to test then? – Jan Slabon Nov 24 '20 at 11:30

0 Answers0