mpdf https 上的图像损坏

问题描述 投票:0回答:5

我正在使用 mpdf 生成 pdf。一切都很好,直到我切换到 https。之后,pdf 仍然可以正确生成,但图像已损坏。他们的源代码在 php 模板上使用 https 协议正确编写。我还尝试仅使用相对路径。没什么。

以下是我班级的示例代码:

  public function save_pdf($translate = false){
    $this->mpdf = new \Mpdf\Mpdf();
    $this->mpdf->CSSselectMedia='mpdf';
    //$this->mpdf->showImageErrors = true; // this will log errors into the php log file

    $ch = curl_init($this->pdf_css_path . '/configurator-pdf.css');
    // this disables ssl check: unsafe
    if($this->disable_ssl_check) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $css = curl_exec($ch);
    curl_close($ch);

    $template = ($translate) ? $this->pdf_template_url : $this->pdf_template_url_it;
    $filename = ($translate) ? $this->pdf_name : $this->pdf_it_name;
    $_POST['cid'] = $this->cid;

    $json = json_encode($_POST);

    $ch = curl_init($template);
    // this disables ssl check: unsafe
    if($this->disable_ssl_check) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $html = curl_exec($ch);
    curl_close($ch);

    $this->mpdf->WriteHTML($css, 1);
    $this->mpdf->WriteHTML($html, 2);

    $pdf = $this->pdf_destination_path . DS . $filename;
    $this->mpdf->Output($pdf, \Mpdf\Output\Destination::FILE);
  }
php ssl curl https mpdf
5个回答
4
投票

在这里找到了解决方案:

mpdf 中带有 https 的图像

我们可以这样设置

//note: using $this only because in my case mpdf is a class prop
$this->mpdf->curlAllowUnsafeSslRequests = true;

它会自动解决,至少对于我上面的程序来说是这样。显然,这不是一个“安全”的解决方案,尤其是在图像和/或内容未知/不可预测的情况下。否则,您应该努力获得工作证书。关于证书设置的两篇好文章是:

https://welaunch.io/plugins/woocommerce-pdf-catalog/faq/images-pdf-displays-red-cross-https-mpdf/

https://medium.com/@f.h.ferreira/file-get-contents-ssl-operation-failed-php-4297ad92977f

最后还特别提供了 https://curl.haxx.se/ 及其证书的链接。不过我没有测试过。


1
投票

我在mpdf类函数file_get_contents_by_curl中找到。 在curl_init函数之后添加这两行。

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

保存 mpdf 后工作正常,图像没有问题。


0
投票

这个问题有点旧(我被 atm 困住的 mpdf 版本也是如此),但最近还有另一个答案,对我来说现有的答案都不起作用(网站/服务器具有有效的 SSL 证书,并且相对路径不成功) ).

我很幸运,我的 pdf 中只有 2 个静态图像,并且我直接控制 HTML,所以我通过将图像转换为 base64 解决了我的问题(使用像 https://www.base64-image.de 这样的工具) /),而不是链接到它们。

这不是一个理想的解决方案,但仍然是一个有效的解决方案,所以我想我应该把它放在这里,以防其他人需要快速修复。


0
投票

感谢您分享此解决方案

$this->mpdf->curlAllowUnsafeSslRequests = true;

今天帮了我的忙:-)


-1
投票

curlAllowUnsafeSslRequests 没有帮助我。但我发现图像变量即使在 https 上也能正常工作..

https://mpdf.github.io/what-else-can-i-do/images.html#image-data-as-a-variable

本质上,您在模板之外获取图像文件的内容,然后将其作为变量传递到那里:

$mpdf->imageVars['myvariable'] = file_get_contents('alpha.png');

在模板中:

<img src="var:myvariable" />
© www.soinside.com 2019 - 2024. All rights reserved.