个性化阅读
专注于IT技术分析

如何解决TCPDF错误:setPage()函数上的页码错误:0

本文概述

对于所有尝试使用TCPDF的开发人员, 以下是在没有遵循文档的情况下使用TCPDF创建第一个PDF期间最常见的错误之一:

TCPDF错误:setPage()函数上的页码错误:0

在本文中, 我们将向你展示为什么在你的代码上引发此异常以及如何轻松解决它。

异常示例

只要你使用的是较旧版本的TCPDF, 以下生成简单PDF的代码就应该引发异常(因为正如你将在”解决方案”区域中看到的那样, 如果未添加第一页, TCPDF会通过自动添加第一页来解决此问题。手动):

<?php

require __DIR__ . '/vendor/autoload.php';
// we supposed that you know how to include the TCPDF class in your document

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set some text to print
$txt = <<<EOD
Exception Example
EOD;

// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

//Close and output PDF document to the browser
$pdf->Output('example.pdf', 'I');

乍一看, 似乎没有什么错, 但是在打印一些需要添加文本以避免异常之前, 有一条重要的代码行。

如前所述, 由于以下原因, 此问题仅在旧版本的TCPDF中出现。你可以在没有页面的PDF上书写吗?我认为不是和TCPDF一样。基于此逻辑, 由于PDF中没有要写入的页面而导致异常, 因此你在文档上至少需要有一页。你可以使用TCPDF的AddPage方法添加页面:

$pdf->AddPage();

因此, 在将某些内容写入PDF之前, 请确保使用AddPage方法将页面添加到HTML:

<?php

require __DIR__ . '/vendor/autoload.php';
// we supposed that you know how to include the TCPDF class in your document

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set some text to print
$txt = <<<EOD
Exception Example
EOD;

// Add first page of the PDF
$pdf->AddPage();

// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

//Close and output PDF document to the browser
$pdf->Output('example.pdf', 'I');

好奇的事实

尽管如果没有添加任何内容, TCPDF会在写入之前自动添加一个页面, 但是如果让PHP消息可见, 则无论如何你都不会在代码中手动添加页面而获得通知(如果可见, 则PDF不会出现)由于某些数据已经被输出消息了):

Notice: Undefined offset: 0 in C:\xampp72\htdocs\leanphp\vendor\tecnickcom\tcpdf\tcpdf.php on line 17162

Notice: Undefined offset: 0 in C:\xampp72\htdocs\leanphp\vendor\tecnickcom\tcpdf\tcpdf.php on line 17529

Notice: Undefined offset: 0 in C:\xampp72\htdocs\leanphp\vendor\tecnickcom\tcpdf\tcpdf.php on line 17982
TCPDF ERROR: Some data has already been output, can't send PDF file

因此, 请确保至少添加一页并防止出现此类问题。

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何解决TCPDF错误:setPage()函数上的页码错误:0

评论 抢沙发

评论前必须登录!