【发布时间】:2018-01-24 07:47:18
【问题描述】:
我正在尝试使用 dompdf 将 HTML 对象导出为 PDF 文档。仅使用文本,我的示例代码可以正常工作。但是,当在 HTML 代码中包含图像时,该图像根本不会显示在 PDF 中。
我从 javascript 中的 ajax 请求中获取 PDF 流。这是我的示例代码:
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 对象。
【问题讨论】:
-
由于您使用
loadHtml()和图像引用的相对路径,Dompdf 将查找相对于正在运行的 PHP 脚本的图像。确保您的图像路径相对于该文件是正确的。或者使用文件系统的绝对路径。另一种选择是使用完整路径(带有协议和域),但您需要确保启用远程资源获取。另请参阅requirements 帮助页面。
标签: javascript php ajax pdf dompdf