Search code examples
phphyperlinkfpdf

fpdf: multiple dynamic links with dynamic varnames


I've been playing with fpdf for a few days, it's nice :) But I'm now trying to code something a little more advanced: Simple links with AddLink and SetLink is ok, but if I try to do the same into a foreach loop:

//Page2:
$index=0;
foreach ($InfosList as $infos) {
  $index+=1;
  $stringC=$infos['name'].", ".$infos['firstname'];
  ${"link_".$index}=$pdf->AddLink();//dynamic varnames
  $pdf->Write(pdf::$linespacing,$StringC,${"link_".$index});
  }

//Page3s:
foreach ($InfosList as $infos) {
  $pdf->AddPage("P","A4");
  $pdf->SetLink(${"link_".$index});
  ...
}

I obtain the error:

Notice: Undefined offset: 0 in .../lib/vendor/fpdf181/fpdf.php on line 1524:

$annots .= sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]>>',$this->PageInfo[$l[0]]['n'],$h-$l[1]*$this->k);

entire fpdf function:

protected function _putpage($n)
{
    $this->_newobj();
    $this->_put('<</Type /Page');
    $this->_put('/Parent 1 0 R');
    if(isset($this->PageInfo[$n]['size']))
        $this->_put(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->PageInfo[$n]['size'][0],$this->PageInfo[$n]['size'][1]));
    if(isset($this->PageInfo[$n]['rotation']))
        $this->_put('/Rotate '.$this->PageInfo[$n]['rotation']);
    $this->_put('/Resources 2 0 R');
    if(isset($this->PageLinks[$n]))
    {
        // Links
        $annots = '/Annots [';
        foreach($this->PageLinks[$n] as $pl)
        {
            $rect = sprintf('%.2F %.2F %.2F %.2F',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]);
            $annots .= '<</Type /Annot /Subtype /Link /Rect ['.$rect.'] /Border [0 0 0] ';
            if(is_string($pl[4]))
                $annots .= '/A <</S /URI /URI '.$this->_textstring($pl[4]).'>>>>';
            else
            {
                $l = $this->links[$pl[4]];
                if(isset($this->PageInfo[$l[0]]['size']))
                    $h = $this->PageInfo[$l[0]]['size'][1];
                else
                    $h = ($this->DefOrientation=='P') ? $this->DefPageSize[1]*$this->k : $this->DefPageSize[0]*$this->k;
                $annots .= sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]>>',$this->PageInfo[$l[0]]['n'],$h-$l[1]*$this->k);
            }
        }
        $this->_put($annots.']');
    }
    if($this->WithAlpha)
        $this->_put('/Group <</Type /Group /S /Transparency /CS /DeviceRGB>>');
    $this->_put('/Contents '.($this->n+1).' 0 R>>');
    $this->_put('endobj');
    // Page content
    if(!empty($this->AliasNbPages))
        $this->pages[$n] = str_replace($this->AliasNbPages,$this->page,$this->pages[$n]);
    $this->_putstreamobject($this->pages[$n]);
}

What can I do, please? Thanks in advance


Solution

  • $index was not defined page3, it's now obvious...

    //Page3s:
    $index=0;
    foreach ($InfosList as $infos) {
      $index+=1;
      $pdf->AddPage("P","A4");
      $pdf->SetLink(${"link_".$index});
      ...
    }