如何在 PHP 中动态放置表格或图像到 pdf

问题描述 投票:0回答:1

我有一个需要通过多项批准的规则的 pdf 文件。在文件(内容)的末尾,我需要:

  1. 在特定位置添加二维码作为电子签名,或者
  2. 在 pdf 的最后内容后面添加一个无边框表格,其中包含一些文本和二维码。这意味着如果 pdf 的最后一个内容以 200 的高度(x)结束,那么该内容应放置在(作为示例)210 的高度(x)中。

这可能吗?

TCPDF

writeHtml
会将生成的 html 放置在页面顶部,而
writeHTMLCell
MultiCell
将需要定义特定的
x
y

我也在 MPDF 中尝试,但它像 TCPDF 一样卡住了。

编写html之前的代码如下所示,

$pageCount = PDF::setSourceFile($file);
$template = PDF::importPage($i);
$size = PDF::getTemplateSize($template);
PDF::AddPage($size['orientation'], array($size['width'], $size['height']));
PDF::useTemplate($template);

// After this, I need to call writeHtml, writeHTMLCell, or MultiCell, but none of those met what I need.
// Or placing an image with PDF::Image also need to define the x and y
...
// PDF::SetX()
// PDF::SetY()
// PDF::Image($qrPath, null, null, 12, 12, 'PNG');
// PDF::WriteHTML(view('document-requests.approver.stamp', ['qr' => $qrPath]), true, false, true, false, '');
PDF::Output($file, 'F');

#编辑

mPDF
的另一件事是,有一个
Overwrite
方法,但它只是覆盖由库本身创建/生成的内容。

php laravel pdf tcpdf mpdf
1个回答
0
投票

答案:

可以使用 TCPDF 或 MPDF 将 QR 码添加到 PDF 中的特定位置,但这需要一些额外的工作,因为没有任何内置功能可以直接满足您的需求。

  1. TCPDF:

要使用 TCPDF 将 QR 码添加到 PDF 中的特定位置,您可以使用以下代码:

<?php

require_once('tcpdf.php');

// Create a new PDF document.
$pdf = new TCPDF();

// Add a new page to the PDF document.
$pdf->AddPage();

// Set the font for the QR code.
$pdf->SetFont('helvetica', '', 10);

// Generate the QR code.
$qrCode = $pdf->write2DBarcode('http://www.example.com', 'QRCODE,H', 10, 10, 30, 30, '', '');

// Position the QR code at the desired location on the page.
$pdf->SetX(100);
$pdf->SetY(100);

// Output the PDF document.
$pdf->Output('example.pdf');

?>
  1. MPDF:

要使用 MPDF 将 QR 码添加到 PDF 中的特定位置,您可以使用代码:

<?php

require_once('mpdf/mpdf.php');

// Create a new PDF document.
$mpdf = new mPDF();

// Set the drawing font for the QR code.
$mpdf->SetDrawingFont('helvetica', '', 10);

// Generate the QR code.
$qrCode = $mpdf->Image($qrPath, null, null, 12, 12, 'PNG');

// Position the QR code at the desired location on the page.
$mpdf->SetXY(100, 100);

// Output the PDF document.
$mpdf->Output('example.pdf');

?>
  • 如果您需要在 PDF 中添加二维码,那么您需要在需要放置的位置添加此代码。
$pdf->WriteHTML('<table><tr><td><img src="qr_code.png" /></td><td>Some text</td></tr></table>');
  • 要将表格放置在 PDF 的末尾,您可以使用 SetY() 函数将 Y 位置设置为 PDF 文档的高度。您可以使用 GetPageHeight() 函数获取 PDF 文档的高度。当您使用 TCPDF 定位表格时,可以使用以下代码:
$pdf->SetY($pdf->GetPageHeight());

将表格放置在 PDF 末尾后,即可输出 PDF 文档。

我希望这对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.