How to solve TCPDF ERROR: Wrong page number on setPage() function: 0

For all the developers that are experimenting with TCPDF, one of the most common errors during the creation of their first PDF with TCPDF without following the documentation, is the following:

TCPDF ERROR: Wrong page number on setPage() function: 0

In this article, we'll show you why this exception is thrown on your code and how to solve it easily.

Example of exception

The following code that generates a simple PDF should throw the exception as long as you're using an older version of TCPDF (because as you will see in the Solution area, TCPDF fixes this by adding automatically the first page if there's no first page added manually):

At first sight, nothing seems to be wrong, but there's an important line before printing some text that needs to be added in order to avoid the exception.

Solution

As mentioned previously, this problem appears only in older versions of TCPDF for the following reason. Could you write on a PDF without pages ? I think not and TCPDF says the same. Based on this logic, the exception is caused because there are no pages to write in the PDF, so you will need to have at least one page on your document. You can add pages with the AddPage method of TCPDF:

$pdf->AddPage();

So before writing some content to the PDF, be sure to add a page to your HTML with the AddPage method:

Curious fact

Although TCPDF adds automatically a page before writing if you didn't add any, you will get anyway without adding a page manually a notice in your code if you let the PHP messages visible (if the notice messages are visible the PDF wouldn't appear anymore due to the some data has already been output message):

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

So be sure to add at least one page and prevent any problem of this kind.