dompdf未在PDF输出中显示图像

时间:2017-08-16 08:44:54

标签: javascript php ajax pdf dompdf

我正在尝试使用dompdf将HTML对象导出为PDF文档。仅使用文本,我的示例代码工作正常。但是,在HTML代码中包含图像时,图像根本不会显示在PDF中。

我在javascript中从ajax请求获取PDF Steam。下面是我的示例代码:

JS:

$(document).ready(function () {
    $('#export-pdf').on("click", function () {
        $.ajax({
            url: "html_pdf_export.php",
            success: function (data) {

                printPDF(data, function (htmlText) {
                    var detailWindow = window.open("", "detailPDF");
                    detailWindow.document.write(htmlText);
                    console.log(htmlText);
                    detailWindow.document.close();
                });
            }
        });
    });
});
function printPDF(data, callback) {
    var pdfText = $.trim(data);
    var htmlText = '<embed width="100%" height="100%" type="application/pdf" src="data:application/pdf,'
        + encodeURI(pdfText) + '"></embed>';
    callback(htmlText);
}

PHP:

$dompdf = new Dompdf();
$dompdf->loadHtml("<h1>Das ist ein Header</h1><p>Das ist ein Absatz unter einem Header.</p>
    <img src='./pic.jpg' style='border: 2px solid black; width: 50%;'>");

$dompdf->render();
$dompdf->stream();

现在我只是尝试流式传输PHP文件中指定的一些硬编码HTML代码,尽管最终目标是通过ajax调用传递DOM对象。

3 个答案:

答案 0 :(得分:0)

尝试使用图像的绝对路径。

答案 1 :(得分:0)

我有几乎相同的问题:如果我使用:

<img src="../ab/media/cd/img1.jpg">它有效,但如果我使用:<img src="http://www.Mypage.com/ab/media/cd/img1.jpg">则不起作用。我希望(必须)能够使用dompdf和第二个链接,这是正确的,当我将其粘贴到浏览器时找到图像。

答案 2 :(得分:0)

一个不错的选择是将图像显示为 base64 字符串,使用辅助函数获取相关图像的绝对路径。这里的一个例子是在 yii2 中,但可以在所有 php 框架中实现。

class DompdfImageUtil{
  public static function display($path){
    $image = base64_encode(file_get_contents($path)); 

    return "data:image/png;base64,$image"; 
  }

用法:

<?= Html::img(DompdfImageUtil::display('@app/web/image.png') ?>