Ниже приведен мой PHP-код для преобразования HTML в PDF, но изображения не отображаются в PDF. Я пытался использовать как локальные пути, так и URL-адреса сервера, оба не отображают изображения в PDF.
<?php
use Dompdf\Options;
//add autoload.inc.php
require_once "./dompdf/autoload.inc.php";
$options = new Options();
$options->set('isRemoteEnabled', true);
// reference the Dompdf namespace
use Dompdf\Dompdf;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
//$dompdf->loadHtml($html);
$page = file_get_contents("certificate.html");
$dompdf->loadHtml($page);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
$dompdf->stream("training-certificate", array("Attachments"=>0));
?>
Ниже приведен код моего файла HTML:
<style>
div.background {
background: #ffffff;
border: 5px solid black;
margin: 10px;
}
div.transbox {
margin: 3px;
background-color: #ffffff;
border: 1px solid black;
}
div.transbox p {
margin: 4%;
color: #000000;
}
#middle {
margin: 5px;
background-color: #ffffff;
border: 1px solid #fff;
}
body{
background-color: #f6f6f6;
}
.logowhite{
float: right;
}
.logo {
clear: right;
text-align: center;
}
</style><link href = "https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/themes/twentytwentyone-child/assets/css/font-awesome.min.css" media = "all" type = "text/css" rel = "stylesheet"/>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"/>
<link href = "https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/themes/twentytwentyone-child/assets/css/main.min2.css" media = "all" type = "text/css" rel = "stylesheet"/>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script><body id = "thank-you" class = "base"><div id = "middle">
<div class = "background">
<div class = "transbox">
<div class = "logowhite"> <img src = "https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/uploads/sites/2/2022/03/org_logo.png" alt = "" /></div>
<div class = "logo"> <img src = "https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/uploads/sites/2/2022/03/nexplanon_logo.png" alt = "" />
<p style = "font-size:2rem;color:#00F;text-transform: uppercase;">'.$fname.' '.$lname.'</p>
<p style = "font-size: 1.25rem;">This certificate serves as confirmation of the completion of the Mandatory Training Module<BR>
on the updated insertion and removal procedures for NEXPLANON.</p>
<div style = "width: 80%;margin: auto;">
<p style = "float: left;font-size: 1.25rem;"><B>Training Date:</B> <span style = "color: #00F;">'.$date.'</span> </p>
<img style = "float: right;" src = "https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/uploads/sites/2/2022/03/signature.png" alt = "" /> </div>
</div>
<p style = "clear: both;margin-bottom: 0%;"><BR>I attested that I completed the Organon-sponsored Mandatory Training Module on the updated insertion and removal procedures for NEXPLANON in its entirety. I understand that only healthcare providers who have completed the
Organon-sponsored Clinical Training Program for NEXPLANON may order, insert, and remove NEXPLANON.<BR><BR>
I certified that I am authorized to perform the procedures entailed in the insertion and removal of NEXPLANON in the
jurisdiction where I practice. I attest that if there are specific state requirements in the state where I practice, I have met all appropriate state conditions including but not limited to collaborative or signing agreement with an MD/DO.<BR><BR>
If I am a resident or student in advanced practice training, I understand that I should only administer NEXPLANON under the supervision of an attending healthcare provider who has also been trained on the procedures to insert and
remove NEXPLANON.</p>
<div style = "margin-bottom: -2%;">
<p style = "font-size: 0.7rem;float: left;">© 2021 Organon group of companies. All rights reserved. ORGANON and the ORGANON Logo are trademarks of the Organon group of companies.</p>
<p style = "float: right;font-size: 0.7rem;">US-XPL-115639 12/21</p>
<p style = "clear: both;margin-bottom: 0%;"> </p>
</div>
</div>
</div>
</div></body>
Пожалуйста, предложите, я уже пробовал библиотеку TCPDF, но есть очень ограниченный CSS, поэтому я сейчас использую DOMPDF.
Поскольку URL-адреса могут указывать куда угодно, а PDF-файлы должны работать не так, вам необходимо встроить все изображение, закодировав его как base64.
как этот пример здесь https://stackoverflow.com/a/8499716/5956589
<div>
<p>Taken from wikpedia</p>
<img src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg= = " alt = "Red dot" />
</div>
Обратите внимание, что формат data:[<mediatype>][;base64],<data>
Обратитесь к https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs, чтобы полностью понять, как это работает.
Круто, я встроил все наше изображение, используя онлайн-сайт «base64.guru/конвертер/кодировать/изображение», а также другие веб-сайты. так это нормально, что мы можем генерировать код для вставки онлайн с любого веб-сайта? а также будет работать на нашем живом веб-сайте?
@Gopal да, это тоже может работать, хотя вы можете сделать это в коде на лету, заменив URL-адреса изображений на base64.
Последний вопрос: теперь мой PDF-файл сгенерирован, но он разделен на 2 страницы вместо одной страницы. Есть ли код для настройки PDF на одной странице формата А4 в DOMPDF? и мой pdf загружается напрямую, а не открывается в браузере, почему?
Пожалуйста, отметьте как ответ, когда будете удовлетворены. чтобы сделать одну страницу, установите размер изображения в теге изображения, а для загрузки вам нужно задать новый вопрос, поскольку браузеры по умолчанию загружают файлы PDF, а не открывают их напрямую, вы можете заглянуть в pdf.js
Пожалуйста, отметьте как ответ, если вы удовлетворены ответом, чтобы облегчить будущим посетителям