You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PrintJS将PHP文件(invoice.php)打印为PDF?

解决PHP项目中用PrintJS将invoice.php转PDF并打印的问题

方案一:直接将PHP渲染的HTML转PDF打印

这种方案无需额外PHP生成PDF,直接用PrintJS的HTML转PDF功能处理渲染后的invoice页面:

  1. 引入PrintJS资源
    下载PrintJS完整版(包含html2canvas、jsPDF依赖)到本地项目,在调用打印函数的页面<head>中添加:

    <script src="/path/to/print.min.js"></script>
    <link rel="stylesheet" href="/path/to/print.min.css">
    

    替换/path/to/为项目中文件的实际路径。

  2. 修改JavaScript打印函数
    你当前代码将type设为pdf是错误的,因为printable指向的是HTML页面URL,应改为html类型,并补充参数确保样式和渲染正常:

    function print_invoice() {
      printJS({
        printable: base_url + "shipment/invoice",
        type: 'html',
        scanStyles: true, // 自动扫描页面样式
        targetStyles: ['*'], // 应用所有页面样式
        pdfOpenParams: { toolbar: '1', statusbar: '0', scrollbar: '0' }, // 控制PDF预览窗口显示
        showModal: true, // 显示加载提示弹窗
        modalMessage: '正在生成PDF,请稍候...'
      });
    }
    
  3. 优化invoice.php的打印样式
    为避免打印时布局错乱,在invoice.php的<style>中添加打印媒体查询:

    @media print {
      body {
        margin: 0;
        width: auto;
        height: auto;
      }
      .content > div {
        float: none !important;
      }
      /* 可添加需要隐藏的非打印元素 */
      .no-print {
        display: none;
      }
    }
    

方案二:PHP端先生成PDF文件再打印

如果需要在服务器端预先生成PDF文件,再用PrintJS打印:

  1. 安装PHP PDF生成库
    以TCPDF为例,通过Composer安装:

    composer require tecnickcom/tcpdf
    
  2. 创建PDF生成接口
    新建generate_invoice_pdf.php文件,用TCPDF渲染invoice内容并输出PDF:

    <?php
    require_once 'vendor/autoload.php';
    
    // 初始化TCPDF
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetCreator('VShip');
    $pdf->SetTitle('VShip Invoice');
    $pdf->SetMargins(15, 15, 15);
    $pdf->SetAutoPageBreak(TRUE, 15);
    
    $pdf->AddPage();
    
    // 捕获invoice.php的HTML内容
    ob_start();
    include 'invoice.php';
    $htmlContent = ob_get_clean();
    
    // 将HTML写入PDF
    $pdf->writeHTML($htmlContent, true, false, true, false, '');
    // 输出PDF到浏览器(也可保存为文件后提供下载链接)
    $pdf->Output('vship_invoice.pdf', 'I');
    ?>
    
  3. 调整JavaScript打印函数
    此时printable指向PDF生成接口的URL,type设为pdf:

    function print_invoice() {
      printJS({
        printable: base_url + "shipment/generate_invoice_pdf",
        type: 'pdf',
        showModal: true,
        modalMessage: '正在加载PDF,请稍候...'
      });
    }
    

内容的提问来源于stack exchange,提问作者aries

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:45:43