【问题标题】:How to write text in source pdf file in mpdf library?如何在 mpdf 库的源 pdf 文件中写入文本?
【发布时间】:2021-02-22 09:42:42
【问题描述】:

我尝试在https://mpdf.github.io/reference/mpdf-functions/writetext.html 中找到解决方案,但我无法找到合适的解决方案。

实际上源 pdf 以在第一个 pdf 页面中添加/写入一行,但它总是在输出中返回 1 个 pdf 页面,其余页面都消失了。真是奇怪的问题。实际上我的 PDF 有多个页面。

这是我的代码。

require_once APPPATH . './libraries/mpdf/vendor/autoload.php';
if (ob_get_contents()) ob_end_clean();
$Text = "This score is for Mr. John Deo";
$mpdf = new \Mpdf\Mpdf();
$mpdf->SetImportUse(); // only with mPDF <8.0
$file = Sample.pdf'; //This PDF have 2 pages
$pagecount = $mpdf->SetSourceFile($file);
$tplId = $mpdf->ImportPage($pagecount);
$mpdf->UseTemplate($tplId);
$mpdf->SetFont('Arial','B', 11);
$mpdf->WriteText(10,10, $Text );
$mpdf->Output('new.pdf', 'F'); //Return 1 page in output with writetext.

你能告诉我这段代码有什么问题吗?此代码仅返回第一页而不是输出中的所有页面。

【问题讨论】:

    标签: pdf mpdf


    【解决方案1】:

    ImportPage 函数导入只有一页 (see the doc here)。

    您可以使用循环来导入源文档的每一页。

    (编辑添加示例代码)

    示例代码:

    • 意味着在调用Output() 方法之前添加。
    • 您必须将$tplId = $mpdf-&gt;ImportPage($pagecount); 替换为$tplId = $mpdf-&gt;ImportPage(1); 才能在第一页写入,因为SetSourceFile() 方法返回源文档中的总页数。
    • 循环从第二页开始,因为您的代码已经导入并写入第一页(参见前面的点)。
    for ($i = 2; $i <= $pagecount; $i++)
    {
        $mpdf->AddPage(); // Add page to output document
        $tplId = $mpdf->ImportPage($i); // Import page as a template
        $mpdf->UseTemplate($tplId); // insert the template in the added page
    }
    

    (样本为inspired by this answer。)

    请注意,这只是一个示例代码,您应该检查源文件是否存在,在运行循环之前检查总页数等。

    【讨论】:

    • 你能不能给我它的示例代码,因为我试过但我申请失败。提前谢谢。
    • @VipulJethva 我编辑了答案以添加示例代码。是不是更清楚了?
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2021-03-13
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多