Karl Viiburg
Karl Viiburg

Reputation: 832

mpdf - images from a url won't load in generated pdf

I'm trying to load images from a http url but they won't display in my generated pdf.

$this->layout = '//layouts/pdftemplate';
$pdf = Yii::app()->toPDF->mpdf();
$pdf->shrink_tables_to_fit = 1;
$pdf->defaultfooterline = false;
$stylesheet = file_get_contents(Yii::app()->basePath.'/../webroot/admin/themes/admin/css/formbuilder-print.css');
$pdf->WriteHTML($stylesheet, 1);
$pdf->WriteHTML($_POST['html_string']);
$pdf->Output(sys_get_temp_dir()."/test.pdf", 'F');

I'm passing the html to the php function in an ajax call. The images are on Amazon CloudFront.

Update

Thanks to Asped and Latheesan Kanes I got the issue resolved. I also used PHP's DOMDocument class to replace the image urls with the local copy of the image. This is for future reference if anyone also runs into a similar issue

$doc = new DOMDocument();
@$doc->loadHTML($_POST['html_string']);
$imgs = $doc->getElementsByTagname('img');

foreach ($imgs as $img){
  $src = $img->getAttribute('src');
  $name = explode('?', basename($src));
  $name = $name[0];
  $tmp = sys_get_temp_dir().'/'.$name;
  copy($src, $tmp);
  $img->setAttribute('src', $tmp);
}

$html = $doc->saveHTML(); // you can write this to the pdf. $pdf->WriteHTML($html);

Upvotes: 3

Views: 3737

Answers (1)

Asped
Asped

Reputation: 3103

I had a similar issue once displaying an SVG file in the pdf.. it would not work. Then I converted it to a PNG (on the fly), stored locally in a temp folder, and passed the temporary file to mDPF, which helped.

UPDATE - Actually now I remember I didn't even had to convert it, I just had to store it locally in a temp folder..

Upvotes: 3

Related Questions