如何使用 PHP codeigniter 以编程方式生成带有我公司徽标的 PDF

How to generate PDF Programmatically with my company logo using PHP codeigniter

我正在尝试使用 dompdf 库创建带有公司徽标的 PDF,但我有一个没有公司徽标的 PDF。我可以试试下面的代码。

欢迎控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('pdf');
    }
    public function index()
    {
        $html = $this->load->view('welcome_message', [], true);
        $this->pdf->createPDF($html, 'mypdf', false);
    }

}

Welcome_view:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<img src="<?php echo base_url() ?>/img/un6.png'">
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/Welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>
</body>
</html>

还包含 dompdf 文件 application/libraries 文件夹:

PDF.php 文件为 dompdf 文件

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once(dirname(__FILE__) . '/dompdf/autoload.inc.php');

class Pdf
{
function createPDF($html, $filename='', $download=TRUE, $paper='A4', $orientation='portrait'){
$dompdf = new Dompdf\DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper($paper, $orientation);
$dompdf->render();
if($download)
$dompdf->stream($filename.'.pdf', array('Attachment' => 1));
else
$dompdf->stream($filename.'.pdf', array('Attachment' => 0));
}
}
?>

我该怎么做

DomPDF 需要 base64 编码的图像才能以 PDF 格式正确显示。

使用此工具将图像转换为 base64 https://www.base64-image.de/

它会给出一个html标签,只需在您的HTML PDF代码中使用它

问题出在这里:

<img src="<?php echo base_url() ?>/img/un6.png'">

DomPDF 需要将所有外部资源引用为文件路径,而不是 URL。 例如,你可以试试这个:

<img src="<?php echo $_SERVER['DOCUMENT_ROOT']; ?>/img/un6.png'">

或者类似的东西:

<img src="<?php echo FCPATH; ?>/img/un6.png'">

(FCPATH 是 Codeigniter 的前端控制器路径...主 index.php 文件的服务器路径,该文件协调 CI 中的所有内容)