如何使用JsBarcode.js生成条形码,并在Yii框架2.0中使用Kartik mPDF将其打印到PDF文件上?

How can I generate barcode with JsBarcode.js and print it on a PDF file using Kartik mPDF within Yii framework 2.0

本文关键字:mPDF Kartik 打印 文件 PDF js JsBarcode 何使用 条形码 框架 Yii      更新时间:2023-09-26

我已经在Yii framework 2.0中安装了Kartik mPDF扩展。下面是控制器中生成PDF文件并将其发送到浏览器的代码片段。

// setup kartik'mpdf'Pdf component
    $pdf = new Pdf([
        'mode' => Pdf::MODE_CORE, 
        'format' => Pdf::FORMAT_A4, 
        'orientation' => Pdf::ORIENT_PORTRAIT, 
        'destination' => Pdf::DEST_BROWSER, 
        // your html content input
        'content' => $this->renderPartial('print-barcode'),  
        'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
        'cssInline' => '.kv-heading-1{font-size:18px}', 
        'options' => ['title' => 'My PDF file'],
        'methods' => [ 
            'SetHeader'=>['My header'], 
            'SetFooter'=>['{PAGENO}'],
        ]
    ]);
    return $pdf->render(); 

我有两个JS文件(JsBarcode.jsCODE128.js),可以在这里找到https://github.com/lindell/JsBarcode为了生成条形码,我需要包含这些JS文件和我的自定义JavaScript代码。在我看来,我通常包括这些文件如下(我的print-barcode.php)。

<?php
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/js/JsBarcode.js', ['depends' => ['yii'web'JqueryAsset::className()]]);
$this->registerJsFile(Yii::$app->urlManager->baseUrl . '/js/Code128.js', ['depends' => ['yii'web'JqueryAsset::className()]]);
$jsGenerateBarcode = 'My custom Javascript code goes here ...';
$this->registerJs($jsGenerateBarcode, $this::POS_END);
?>

所有包含的JavaScript代码没有任何效果,因为它是一个PDF文件,而不是一个网页。如何打印JsBarcode.jsCODE128.js生成的条码,并将其传递到kartik'mpdf'Pdf;生成的PDF文件上?

抱歉这么晚了,但这对我有用。你应该首先用这些信息创建一个视图,然后使用renderPartial并将其发送到mpdf。

My View包含:

<script src="<?=yii::$app->params['rootUrl']?>/js/JsBarcode.code128.min.js"></script>
<p>Safety is Everyone's Responsibility</p>
<p><barcode code="<?=$model->qrcode?>" type="C128A" class="barcode" size="0.8" /></p>

And to test:

return $this->renderPartial('_print-view',['model'=>$myModel]);
最后打印pdf(我正在打印徽章,所以我在玩边距):
$mpdf = new 'Mpdf'Mpdf([  
//'mode' => 'c'
'margin_left' => 0,
'margin_right' => 0,
'margin_top' => 0,
'margin_bottom' => 0,
'format' => [54,86],
]);
$mpdf->SetTitle('Badge: '.$myModel->badge_number);
$mpdf->WriteHTML($this->renderPartial('_print-view',['model'=>$myModel,'page'=>1]));
$mpdf->AddPage('L');
$mpdf->WriteHTML($this->renderPartial('_print-view',['model'=>$myModel,'page'=>2]));
$mpdf->Output($badge_number,'I');