DOMPDF 版本 1.1.1
我尝试了上述所有选项,唯一对我有用的方法是:
对于绝对路径(例如:https://website/image.jpg),我必须:
#1 - 使用这些选项:
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$options->set('tempDir', '/tmp'); //folder name and location can be changed
$dompdf = new Dompdf($options);
#2 -在添加上述行的 php 代码的同一级别创建此tmp文件夹。
对于相对路径(例如:/contents/test_image.jpg),我必须:
#1 - 使用这些选项:
$options = new Options();
$options->set('tempDir', '/tmp');
$options->set('chroot', __DIR__);
$dompdf = new Dompdf($options);
#2 -在添加上述行的 php 代码的同一级别创建此tmp文件夹(如绝对路径)
最后,为了使用绝对路径和相对路径,我的代码是这样的:
<?php
use Dompdf\Dompdf;
use Dompdf\Options;
require __DIR__ . "/vendor/autoload.php";
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$options->set('tempDir', '/tmp');
$options->set('chroot', __DIR__);
$dompdf = new Dompdf($options);
ob_start();
require __DIR__ . "/contents/my_html.php";
$dompdf->loadHtml(ob_get_clean());
$dompdf->setPaper("A4", "portrait");
$dompdf->render();
$dompdf->stream("file.pdf", ['Attachment' => false]);
我的项目结构是这样的:
pdftest/
|__contents/
| |__my_html.php
| |__jpg_test.jpg
|__tmp/
|__vendor/* //composer stuff
|__index.php
我的 html 看起来 index.php 这个
<html>
<header>
<style>
body { display:flex; flex-direction:column; align-items: center; justify-content: center; }
table { border: 1px solid #a1a1a1; }
table th { border-bottom: 1px solid #a1a1a1; }
</style>
</header>
<body>
<table>
<tr>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
<th>column 4</th>
</tr>
<tr>
<td>Data 1</td>
<td>
<img width="40" src="contents/jpg_test.jpg" alt=""/>
<img width="40" src="https://cdn.pixabay.com/photo/2021/10/14/15/11/cathedral-6709412_960_720.jpg" alt=""/>
</td>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</table>
</body>
</html>