Reputation: 57
I'm trying to use dompdf to export HTML objects as PDF document. Using text only, my example code works fine. However, when including an image in the HTML code, the image simply doesn't show up in the PDF.
I'm getting the PDF steam from an ajax request in javascript. Heres my example code:
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();
Right now I am just trying to stream some hard-coded HTML code specified in the PHP file, although the end goal would be to render DOM-objects trasmitted via the ajax call.
Upvotes: 1
Views: 9382
Reputation: 154
A good option is to display your image as a base64 string, using a helper function that takes an absolute path of the image in question. An example here is in yii2 but can be implemented across all php frameworks.
class DompdfImageUtil{
public static function display($path){
$image = base64_encode(file_get_contents($path));
return "data:image/png;base64,$image";
}
Usage:
<?= Html::img(DompdfImageUtil::display('@app/web/image.png') ?>
Upvotes: 2
Reputation: 1
I have nearly the same problem: if I use:
<img src="../ab/media/cd/img1.jpg">
it works, but if I use: <img src="http://www.Mypage.com/ab/media/cd/img1.jpg">
it does not work. I want(must) be able to use dompdf with the second link, which is correct and the image is found when I paste it to the browser.
Upvotes: 0