首页 > 解决方案 > 如何使用 PHP codeigniter 以编程方式生成带有我公司徽标的 PDF

问题描述

我正在尝试使用 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);
    }

}

欢迎观看:

<?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 文件夹:

dompdf 文件的 PDF.php 文件

<?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));
}
}
?>

我怎样才能做到这一点

标签: phpcodeigniterdompdf

解决方案


问题在这里:

<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 中编排所有内容)


推荐阅读