DOMPDF版本1.1.1
我尝试了上述所有选项,唯一有效的方法是:
对于绝对路径(例如:https://website/image.jpg),我必须执行以下操作:
#1 - 使用这些选项:
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$options->set('tempDir', '/tmp');
$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
table th { border-bottom: 1px solid
</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>