Tcpdf error some data has already been output can t send pdf file

Learn why this error appears when you try to generate a PDF from HTML using TCPDF and how to get rid out of it.

Learn why this error appears when you try to generate a PDF from HTML using TCPDF and how to get rid out of it.

Fighting with the widely known fatal error of TCPDF? The error of «Some data has already been output, can’t send PDF file» refers to the output buffer of PHP. As you may know as a PHP developer, there is code that generates output in PHP and code that not, for example imagine a method namely getId that returns a number:

getId();
// [no output]

echo getId(); 
// Output: 1

So, the conflict with TCPDF is that the library itself once you try to generate the PDF and throw it in the browser using the following code:

<?php

$pdf->Output('example_006.pdf', 'I');

There is surely something in your code that is sending some text or data to the output buffer of PHP before the PDF and therefore the exception is thrown, this is automatically made by the library to prevent the corruption of the generated PDF.

Example of error

To trigger our error in some code with TCPDF, using print_r or var_dump to some value will trigger the error. This happens as well if you use echo or if PHP is throwing a warning, deprecation notice or other kind of errors:

<?php 

require __DIR__.'../vendor/autoload.php';

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

$pdf->SetFont("helvetica", '', 10);
 
$pdf->AddPage();

// Important: this will prevent the generation of the PDF in the browser
// as we are filling the output buffer of PHP
var_dump(array(
    "test" => "demo"
));
 
// create some HTML content
$html = '<h1>HTML Example</h1>
<h2>List</h2>
List example:
<ol>
    <li><b>bold text</b></li>
    <li><i>italic text</i></li>
    <li><u>underlined text</u></li>
    <li><b>b<i>bi<u>biu</u>bi</i>b</b></li>
    <li><a href="http://www.tecnick.com" dir="ltr">link to http://www.tecnick.com</a></li>
    <li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.<br />Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</li>
    <li>SUBLIST
        <ol>
            <li>row one
                <ul>
                    <li>sublist</li>
                </ul>
            </li>
            <li>row two</li>
        </ol>
    </li>
    <li><b>T</b>E<i>S</i><u>T</u> <del>line through</del></li>
    <li><font size="+3">font + 3</font></li>
    <li><small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal</li>
</ol>
</div>';

// Output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
 
$pdf->lastPage();
 
$pdf->Output('example_006.pdf', 'I');

The execution of the previous code would generate the following output in the browser:

array(1) { ["test"]=> string(4) "demo" } TCPDF ERROR: Some data has already been output, can't send PDF file

Solution

The first and most common solution, is to search on your code what is the line or code that is generating some output before TCPDF and remove it (mentioned methods as print_r, var_dump, echo etc). If there are no method that generate output but Warnings, deprecation notices or errors from PHP, you need to solve them first. After doing that, the PDF should be generated without any issue.

If for some reason, you cannot track from where the output is being generated, then you can use a very simple trick (however very tricky) that is cleaning the output buffer of PHP before generating the PDF with the Output method of TCPDF:

// Clean any content of the output buffer
ob_end_clean();

// Send the PDF !
$pdf->Output('example_006.pdf', 'I');

This will immediately work, however it is a problem if you want to debug the content of variables in the browser with the mentioned methods that generate content in the output. For example, if you clean the output buffer but you want to see the content of a variable with the following code:

// Debug the content of some variable
var_dump(array(
    "data" => "demo"
));

// Clean any content of the output buffer
ob_end_clean();

// Send the PDF !
$pdf->Output('example_006.pdf', 'I');

You will never see the output of var_dump as we are cleaning the buffer after. So the best solution is to search from where the output buffer is being filled with undesired data and remove it.

Happy coding !

same result.
the system is centos 7 with remi 7.2
with remi 5.6 the problem was also there
the productive system is more or less the same with c7 , glpi 9.1 and php 5.4 . there i dont have the problem.

here some sys infos

[code]
 
GLPI 9.2.3 (/glpi => /data/glpi)
Installation mode: TARBALL

Server

 
Operating system: Linux muc1glpiv01p 3.10.0-862.3.2.el7.x86_64 #1 SMP Mon May 21 23:36:36 UTC 2018 x86_64
PHP 7.2.6 apache2handler (Core, PDO, Phar, Reflection, SPL, SimpleXML, Zend OPcache, apache2handler, apcu, bcmath, bz2,
	calendar, ctype, curl, date, dom, exif, fileinfo, filter, ftp, gd, gettext, hash, iconv, igbinary, imap, intl, json, json_post,
	jsond, ldap, libxml, lzf, mbstring, mcrypt, mysqli, mysqlnd, openssl, pcre, pdo_mysql, pdo_sqlite, posix, session, shmop, snmp,
	soap, sockets, sqlite3, standard, sysvmsg, sysvsem, sysvshm, tidy, tokenizer, wddx, xml, xmlreader, xmlrpc, xmlwriter, xsl, zip,
	zlib)
Setup: max_execution_time="30" memory_limit="128M" post_max_size="8M" safe_mode="" session.save_handler="files"
	upload_max_filesize="2M" 
Software: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.2.6 ()
	Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Server Software: MariaDB Server
	Server Version: 10.2.15-MariaDB
	Server SQL Mode: 
	Parameters: glpi@127.0.0.1/glpi
	Host info: 127.0.0.1 via TCP/IP
	
mysqli extension is installed
ctype extension is installed
fileinfo extension is installed
json extension is installed
mbstring extension is installed
zlib extension is installed
curl extension is installed
gd extension is installed
simplexml extension is installed
xml extension is installed
ldap extension is installed
imap extension is installed
Zend OPcache extension is installed
APCu extension is installed
xmlrpc extension is installed
OK/data/glpi/config : OK
OK/data/glpi/files : OK
OK/data/glpi/files/_dumps : OK
OK/data/glpi/files/_sessions : OK
OK/data/glpi/files/_cron : OK
OK/data/glpi/files/_graphs : OK
OK/data/glpi/files/_lock : OK
OK/data/glpi/files/_plugins : OK
OK/data/glpi/files/_tmp : OK
OK/data/glpi/files/_cache : OK
OK/data/glpi/files/_rss : OK
OK/data/glpi/files/_uploads : OK
OK/data/glpi/files/_pictures : OK
OK/data/glpi/files/_log : OK
Web access to the files directory should not be allowed but this cannot be checked automatically on this instance.
Make sure acces to error log file is forbidden; otherwise review .htaccess file and web server configuration.OKSELinux mode is Disabled

Libraries

 
htmLawed version 1.2.4 in (/data/glpi/lib/htmlawed)
phpCas version 1.3.5 in (/data/glpi/vendor/jasig/phpcas/source)
PHPMailer version 5.2.26 in (/data/glpi/vendor/phpmailer/phpmailer)
SimplePie version 1.5.1 in (/data/glpi/vendor/simplepie/simplepie/library)
TCPDF version 6.2.16 in (/data/glpi/vendor/tecnickcom/tcpdf)
michelf/php-markdown in (/data/glpi/vendor/michelf/php-markdown/Michelf)
true/punycode in (/data/glpi/vendor/true/punycode/src)
iacaml/autolink in (/data/glpi/vendor/iamcal/lib_autolink)
sabre/vobject in (/data/glpi/vendor/sabre/vobject/lib)

LDAP directories

 
Server: 'xxxxx', Port: '389', BaseDN: 'xxxx', Connection filter:
		'xxx.... '


SQL replicas

 
Not active

Notifications

 
Way of sending emails: SMTP (anonymous@localhost)

Mails receivers

 
Name: 'glpi@xxxx....' Active: Yes
	Server: '{xxxx..../imap}' Login: 'glpi' Password: Yes

Plugins list

 
	accounts             Name: Accounts                       Version: 2.3.2      State: Not activated
	fields               Name: Additionnal fields             Version: 1.7.2      State: Not activated
	news                 Name: Alerts                         Version: 1.3.5      State: Not activated
	appliances           Name: Appliances                     Version: 2.3.2      State: Not activated
	financialreports     Name: Asset situation                Version: 2.4.1      State: Not activated
	badges               Name: Badges                         Version: 2.3.0      State: Not activated
	barcode              Name: Barcode                        Version: 2.1.0      State: Not activated
	positions            Name: Cartography                    Version: 4.4.0      State: Not activated
	certificates         Name: Certificates                   Version: 2.3.0      State: Not activated
	connections          Name: Connections                    Version: 9.2        State: Not activated
	consumables          Name: Consumable request             Version: 1.3.1      State: Not activated
	credit               Name: Credit vouchers                Version: 1.1.1      State: Not activated
	dashboard            Name: Dashboard                      Version: 0.9.2      State: Not activated
	databases            Name: Databases                      Version: 2.0.0      State: Not activated
	domains              Name: Domains                        Version: 1.9.0      State: Not activated
	environment          Name: Environment                    Version: 2.1.0      State: Not activated
	escalade             Name: Escalation                     Version: 2.2.2      State: Not activated
	datainjection        Name: File injection                 Version: 2.5.1      State: Not activated
	formvalidation       Name: Form Validation                Version: 0.2.3      State: Not activated
	formcreator          Name: Forms                          Version: 2.6.3      State: Not activated
	fusioninventory      Name: FusionInventory                Version: 9.2+2.0    State: Not activated
	openvas              Name: GLPi openvas Connector         Version: 1.1.0      State: Not activated
	resources            Name: Human Resources                Version: 2.4.3      State: Not activated
	geninventorynumber   Name: Inventory number generation    Version: 2.2.0      State: Not activated
	mailanalyzer         Name: Mail Analyzer                  Version: 1.3.8      State: Not activated
	mreporting           Name: More Reporting                 Version: 1.4.0      State: Not activated
	satisfaction         Name: More satisfaction              Version: 1.2.1      State: Not activated
	moreticket           Name: More ticket                    Version: 1.3.3      State: Not activated
	mydashboard          Name: My Dashboard                   Version: 1.5.0      State: Not activated
	nebackup             Name: nebackup                       Version: 2.2.1      State: Not activated
	archires             Name: Network Architectures          Version: 2.5.1      State: Not activated
	genericobject        Name: Objects management             Version: 2.5.1      State: Not activated
	order                Name: Orders management              Version: 2.0.1      State: Not activated
	pdf                  Name: Print to pdf                   Version: 1.3.1.1    State: Not activated
	printercounters      Name: Printer counters               Version: 1.4.0      State: Not activated
	processmaker         Name: Process Maker                  Version: 3.2.8      State: Not activated
	purgelogs            Name: Purge history                  Version: 1.3.0      State: Not activated
	racks                Name: Rack enclosures management     Version: 1.8.0      State: Not activated
	reports              Name: Reports                        Version: 1.11.3     State: Not activated
	seasonality          Name: Seasonalities                  Version: 1.3.0      State: Not activated
	shellcommands        Name: Shell Commands                 Version: 2.1.0      State: Not activated
	manufacturersimports Name: Suppliers imports              Version: 2.0.0      State: Not activated
	surveyticket         Name: Survey                         Version: 9.2+1.1    State: Not activated
	tag                  Name: Tag Management                 Version: 2.1.1      State: Not activated
	tasklists            Name: Tasks list                     Version: 1.2.0      State: Not activated
	timezones            Name: Timezones                      Version: 2.2.0      State: Not installed
	typology             Name: Typologies                     Version: 2.4.0      State: Not activated
	webapplications      Name: Web applications               Version: 2.4.0      State: Not activated

I’ve installed the Printer-friendly Pages version 6.x-1.0-rc5 with tcpdf_php5 version 4.0.006 as described in the documentation on drupal 6.3. The example pages of tcpdf generates PDF-files corectly but when I try to create a PDF-File by clicking on the PDF-Create Link I get the following error: TCPDF error: Some data has already been output, can’t send PDF file.

Please help.

Comments

jcnventura’s picture

Status: Active » Postponed (maintainer needs more info)

Hi,

I never saw that error. It’s definitively a problem with TCPDF. Can you try dompdf instead?

João

  • Log in or register to post comments

xurubo93’s picture

I cannot use dompdf, because it doesn’t support UTF8.

  • Log in or register to post comments

jcnventura’s picture

From what I have been able to find out, TCPDF shows that error when some kind of error was produced and logged before the actual PDF generation. Unfortunately, it can do so in more than one situation and I know of no way of finding out which was the actual error.

Without more info, I really cant’ help you.

João

  • Log in or register to post comments

jcnventura’s picture

No further info received in 2 weeks, closing the issue.

  • Log in or register to post comments

jcnventura’s picture

Status: Postponed (maintainer needs more info) » Closed (fixed)
  • Log in or register to post comments

Alpha5’s picture

  • Log in or register to post comments

jannalexx’s picture

same error here…
try this in print_pdf.pages.inc

in print_pdf.pages.inc
insert:

//Change To Avoid the PDF Error 
  ob_end_clean();

just before
$pdf->Output($filename, $output_dest);

  • Log in or register to post comments

jcnventura’s picture

Status: Closed (fixed) » Needs review

Note that this doesn’t really solve the problem.. TCPDF reported some kind of error/warning and the PDF will have problems..

However, I would like to know if you used the above line, and if so, what were the results.

João

  • Log in or register to post comments

Alpha5’s picture

It work fine for me. Add this line and I get the pdf file support UTF8.

  • Log in or register to post comments

jcnventura’s picture

Status: Needs review » Postponed (maintainer needs more info)

According to the documentation for ob_end_clean, it turns off the output buffer. That may have severe side-effects inside TCPDF. Can you try ob_clean instead and tell me if it also solves your problem?

João

  • Log in or register to post comments

Alpha5’s picture

Try ob_clean() also get correct pdf file. Thanks!

  • Log in or register to post comments

jcnventura’s picture

Status: Postponed (maintainer needs more info) » Fixed

Added ob_clean() to CVS.

João

  • Log in or register to post comments

chaimkut’s picture

Version: 6.x-1.0-rc5 » 6.x-1.5
Status: Fixed » Active

Hi
I have the latest 6.x-1.5 version of the Print module, and am experiencing the bug described above. I have attempted both suggested fixes of ob_end_clean() and ob_clean() but neither of them worked. The big difference in my configuration is that I’m using tcpdf_php4 on a PHP 4.3.11 system. I am able to successfully create the examples in tcpdf’s ‘examples’ folder. Any ideas?

Edit: I installed the latest Dev cut of the Print module and I no longer receive this error. Now, when I try to retrieve a PDF for a 5 line article in UTF8, mty browser fails to download the entire 1.7 MB file. It usually gets to 1 MB or 1.5 MB and then fails. I’m suspecting that at this point it’s a memory issue when trying to hold such a large file in memory at once. I will update if I figure anything else out.

  • Log in or register to post comments

jcnventura’s picture

Status: Active » Closed (fixed)

Two weeks without furhter info.. Closing the issue.

  • Log in or register to post comments

firfin’s picture

Version: 6.x-1.10 » 6.x-1.5
Status: Closed (fixed) » Fixed

I am experiencing the same problem. Using the latest print (6.x-1.5) tcpdf (4.6.025) and drupal (6.13).
My version of print already had the

 // try to recover from any warning/error
  ob_clean();

And I also tried ob_end_clean() .

After reading the tcpdf forums I realized I had some whitespace and newliness at the end of my template.php file. Nothing should be outputted before pdf->output is called! Once I removed the fluff is everything worked fine.

Probably the solution for others still experiencing problem after the ob_clean fix.
(so I mark this as fixed, hope that’s ok)

  • Log in or register to post comments

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

nsvwa’s picture

Version: 6.x-1.5 » 6.x-1.10

I’m using print (6.x-1.10) tcpdf (4.8.032) and drupal (6.15)
I found that if I edit code (ex. print_pdf.module or print_pdf.pages.inc) and save in UTF format, I’ll get this error.
I must keep code in ANSI format, but I can use UTF for template file (ex. print.node-node_example.tpl.php) for thai language.

  • Log in or register to post comments

hacknslash’s picture

The ANSI save fixed this for me, too. Didn’t try the ob_clean solution, so can’t vouch for it.
— Cheers

  • Log in or register to post comments

pankaj01’s picture

I had similar error.
To resolve this I had to remove the closing php tags ‘>’ in the end of file

  • Log in or register to post comments

marthinal’s picture

I fixed it cleaning a whitespace line at the beggining of a custom module.

  • Log in or register to post comments

seers’s picture

Version: 6.x-1.5 » 6.x-1.10
Status: Fixed » Closed (fixed)

This error means HTML header has been output before creating the PDF file.
Just remove any HTML headers and HTML tags in the PDF building pages and it works!

  • Log in or register to post comments

svergeylen’s picture

I added ob_start() before Output() to clear the PHP buffer how contains already 6 elements… even if I had no print or echo before Output()…. This solved my problem but the use of ob_clean() didn’t help

  • Log in or register to post comments

gaurav.matta’s picture

ob_start();
$tcpdf->output($filename, $output_dest);
ob_end_flush();

  • Log in or register to post comments

malveslin’s picture

coloque require_once(dirname(__FILE__).’/html2pdf/html2pdf.class.php’);
na primeira linha php como você faz com as sessões !

  • Log in or register to post comments

Борьба с широко известной фатальной ошибкой TCPDF? Ошибка «Некоторые данные уже выведены, не удается отправить файл PDF» относится к выходному буферу PHP. Как вы, возможно, знаете, как разработчик PHP, есть код, который генерирует вывод в PHP, и код, который, например, не представляет метод, а именно getId который возвращает число:

getId();
// [no output]
echo getId();
// Output: 1

Итак, конфликт с TCPDF заключается в том, что сама библиотека, когда вы пытаетесь сгенерировать PDF и выбросить его в браузер, используя следующий код:

Output('example_006.pdf', 'I');

В вашем коде наверняка есть что-то, что отправляет некоторый текст или данные в выходной буфер PHP перед PDF, и поэтому создается исключение, это автоматически делается библиотекой, чтобы предотвратить повреждение созданного PDF.

Пример ошибки

Чтобы вызвать нашу ошибку в некотором коде с TCPDF, используя print_r или же var_dump к некоторому значению вызовет ошибку. Это также случается, если вы используете echo или если PHP выдает предупреждение, уведомление об устаревании или другие виды ошибок:

SetFont("helvetica", '', 10);
$pdf->AddPage();
// Important: this will prevent the generation of the PDF in the browser
// as we are filling the output buffer of PHP
var_dump(array(
"test" => "demo"
));
// create some HTML content
$html = 'HTML Example

List

List example:
  1. bold text
  2. italic text
  3. underlined text
  4. bbibiubib
  5. link to http://www.tecnick.com
  6. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
  7. SUBLIST
    1. row one
      • sublist
    2. row two
  8. TEST line through
  9. font + 3
  10. small text normal small text normal subscript normal superscript normal
'; // Output the HTML content $pdf->writeHTML($html, true, false, true, false, ''); $pdf->lastPage(); $pdf->Output('example_006.pdf', 'I');

Выполнение предыдущего кода будет генерировать следующий вывод в браузере:

array(1) { ["test"]=> string(4) "demo" } TCPDF ERROR: Some data has already been output, can't send PDF file

Решение

Первое и наиболее распространенное решение — это поиск в вашем коде строки или кода, генерирующих какой-либо вывод перед TCPDF, и удаление его (упомянутые методы как print_r, var_dump, echo и т. Д.). Если нет никакого метода, который генерирует выходные данные, кроме предупреждений, уведомлений об устаревании или ошибок от PHP, вам нужно сначала решить их. После этого PDF должен быть создан без каких-либо проблем.

Если по какой-то причине вы не можете отследить, откуда генерируется вывод, то вы можете использовать очень простой прием (хотя и очень хитрый), который очищает буфер вывода PHP перед генерацией PDF с помощью метода Output из TCPDF:

// Clean any content of the output buffer
ob_end_clean();
// Send the PDF !
$pdf->Output('example_006.pdf', 'I');

Это немедленно сработает, однако это проблема, если вы хотите отладить содержимое переменных в браузере с помощью упомянутых методов, которые генерируют содержимое в выводе. Например, если вы очищаете выходной буфер, но хотите видеть содержимое переменной с помощью следующего кода:

// Debug the content of some variable
var_dump(array(
"data" => "demo"
));
// Clean any content of the output buffer
ob_end_clean();
// Send the PDF !
$pdf->Output('example_006.pdf', 'I');

Вы никогда не увидите результат var_dump как мы чистим буфер после. Таким образом, наилучшее решение — найти, откуда выходной буфер заполняется нежелательными данными, и удалить его.

  • Summary

  • Files

  • Reviews

  • Support

  • Code

  • Tickets ▾

    • Bugs
    • Patches
    • Feature Requests
  • News

  • Discussion

  • Donate

Menu

getting «TCPDF ERROR: Some data has already been output, can’t send PDF file»


Created:

2014-04-05

Updated:

2014-04-16

  • Wayne Sewell

    I am not sure where I am writing to the output stream before calling $pdf->Output.
    I did have a print statement for the HTML, but that was commented out.
    I basically took the example and replaced the canned table with my own.

    Here is the redone example:

    <?php
    //============================================================+
    // File name   : example_048.php
    // Begin       : 2009-03-20
    // Last Update : 2013-05-14
    //
    // Description : Example 048 for TCPDF class
    //               HTML tables and table headers
    //
    // Author: Nicola Asuni
    //
    // (c) Copyright:
    //               Nicola Asuni
    //               Tecnick.com LTD
    //               www.tecnick.com
    //               info@tecnick.com
    //============================================================+
    
    /**
     * Creates an example PDF TEST document using TCPDF
     * @package com.tecnick.tcpdf
     * @abstract TCPDF - Example: HTML tables and table headers
     * @author Nicola Asuni
     * @since 2009-03-20
     */
    
    // Include the main TCPDF library (search for installation path).
    require_once('tcpdf_include.php');
    
        $field_lengths[] = "50"; 
        $field_lengths[] = "200";
        $field_lengths[] = "40";
        $field_lengths[] = "40";
        $field_lengths[] = "40";
        $field_lengths[] = "40";
        $field_lengths[] = "40";
        $field_lengths[] = "200";
    
        $field_names[] = "Date";
        $field_names[] = "Job Name";
        $field_names[] = "Client Code";
        $field_names[] = "Client PO Number";
        $field_names[] = "Your PO Number";
        $field_names[] = "Job Number";
        $field_names[] = "Amount";
        $field_names[] = "Remarks";
    
        $field_orientations[] = "center";
        $field_orientations[] = "left";
        $field_orientations[] = "center";
        $field_orientations[] = "center";
        $field_orientations[] = "center";
        $field_orientations[] = "center";
        $field_orientations[] = "right";
        $field_orientations[] = "left";
    
        function generate_field($width, $align, $val)
    
        {
            return '<td align="' . $align . '" width="' . $width . '">' . $val . '</td>';
        }
    
        function generate_row($invals, $field_orientations, $field_lengths, $header=0, $style='')
    
        {
    
            if ($style != '') $html = '<tr style="' . $style . '">';
            else $html = '<tr>';
            $field_orientation = "center";
            $index = 0;
            $vals = $invals;
            foreach ($vals as $val) {
                if (!$header) $field_orientation = $field_orientations[$index];
                $length = $field_lengths[$index];
                $html .= generate_field($length, $field_orientation, $val);
                $index++;
            }
    
            $html .= '</tr>';
    
            return $html;
    
        }
    
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Nicola Asuni');
    $pdf->SetTitle('TCPDF Example 048');
    $pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
    
    // set default header data
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 048', PDF_HEADER_STRING);
    
    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    
    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    
    // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    
    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    
    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    
    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
    }
    
    // ---------------------------------------------------------
    
    // set font
    $pdf->SetFont('helvetica', 'B', 20);
    
    // add a page
    $pdf->AddPage();
    
    $pdf->Write(0, 'Invoice for Joe Blow of Insane Clown Posse', '', 0, 'L', true, 0, false, false, 0);
    
    $pdf->SetFont('helvetica', '', 8);
    
    // -----------------------------------------------------------------------------
    
    // Table with rowspans and THEAD
        $tbl = '<table border="1" cellpadding="2" cellspacing="2">';
        $tbl .= '<thead>';
        $tbl .= generate_row($field_names,"", $field_lengths,1,"background-color:#FFFF00;color:#0000FF;");
        $tbl .= '</tr></thead>';
        $tbl .= generate_row(explode("~","Mar 1, 2013~My Terrific Job~K47~4405~20131~1105~12.34~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
        $tbl .= generate_row(explode("~","Mar 1, 2013~Buncha Junk~J53~606606~48132~34567~106.50~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
     $tbl .= generate_row(explode("~","Mar 1, 2013~Insane Document~LLX035~48440~30378~222~11.50~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
     $tbl .= generate_row(explode("~","Mar 1, 2013~My Manifesto~KNJ222~414~8075~73009~50.25~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
     $tbl .= generate_row(explode("~","Mar 1, 2013~I dont believe it~1105~23101~87601~93340~232.32~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
     $tbl .= generate_row(explode("~","Mar 1, 2013~What, Me Worry?~KRX455~959~91730~50857~41.41~request 104294501, minimum charge per job of $23.00"), $field_orientations, $field_lengths);
    
        $tbl .= '</table>';
    //print($tbl);
    //exit(0);
    
    $pdf->writeHTML($tbl, true, false, false, false, '');
    
    $pdf->writeHTML($tbl, true, false, false, false, '');
    
    $pdf->writeHTML($tbl, true, false, false, false, '');
    
    $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
        $pdf->writeHTML($tbl, true, false, false, false, '');
    
    // -----------------------------------------------------------------------------
    
    //Close and output PDF document
    $pdf->Output('example_048_honk.pdf', 'I');
    
    //============================================================+
    // END OF FILE
    //============================================================+
    

    At this point I haven’t changed that much from the original example.
    I am just trying to get my format settled before
    continuing on with generating real data. I apologize for the weird indentation, due to
    rebellious language-sensitive editor. Rather than having you figure out the actual HTML
    generated by the PHP functions, here it is:

    <table border="1" cellpadding="2" cellspacing="2">
        <thead>
          <tr style="background-color:#FFFF00;color:#0000FF;">
            <td align="center" width="50">Date</td>
    
            <td align="center" width="200">Job Name</td>
    
            <td align="center" width="40">Client Code</td>
    
            <td align="center" width="40">Client PO Number</td>
    
            <td align="center" width="40">Your PO Number</td>
    
            <td align="center" width="40">Job Number</td>
    
            <td align="center" width="40">Amount</td>
    
            <td align="center" width="200">Remarks</td>
          </tr>
        </thead>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">My Terrific Job</td>
    
          <td align="center" width="40">K47</td>
    
          <td align="center" width="40">4405</td>
    
          <td align="center" width="40">20131</td>
    
          <td align="center" width="40">1105</td>
    
          <td align="right" width="40">12.34</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">Buncha Junk</td>
    
          <td align="center" width="40">J53</td>
    
          <td align="center" width="40">606606</td>
    
          <td align="center" width="40">48132</td>
    
          <td align="center" width="40">34567</td>
    
          <td align="right" width="40">106.50</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">Insane Document</td>
    
          <td align="center" width="40">LLX035</td>
    
          <td align="center" width="40">48440</td>
    
          <td align="center" width="40">30378</td>
    
          <td align="center" width="40">222</td>
    
          <td align="right" width="40">11.50</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">My Manifesto</td>
    
          <td align="center" width="40">KNJ222</td>
    
          <td align="center" width="40">414</td>
    
          <td align="center" width="40">8075</td>
    
          <td align="center" width="40">73009</td>
    
          <td align="right" width="40">50.25</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">I dont believe it</td>
    
          <td align="center" width="40">1105</td>
    
          <td align="center" width="40">23101</td>
    
          <td align="center" width="40">87601</td>
    
          <td align="center" width="40">93340</td>
    
          <td align="right" width="40">232.32</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
    
        <tr>
          <td align="center" width="50">Mar 1, 2013</td>
    
          <td align="left" width="200">What, Me Worry?</td>
    
          <td align="center" width="40">KRX455</td>
    
          <td align="center" width="40">959</td>
    
          <td align="center" width="40">91730</td>
    
          <td align="center" width="40">50857</td>
    
          <td align="right" width="40">41.41</td>
    
          <td align="left" width="200">request 104294501, minimum charge per job of
          $23.00</td>
        </tr>
      </table>
    

    So I’m not sure where it gets the idea that I have output anything.

    As a side note, I am getting a lot of these warnings:

    Warning: array_push() expects parameter 1 to be array, null given in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 16878
    Warning: array_push() expects parameter 1 to be array, null given in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 16878
    Warning: array_push() expects parameter 1 to be array, null given in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 16878
    Warning: array_push() expects parameter 1 to be array, null given in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 16878
    Warning: Invalid argument supplied for foreach() in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 19375
    Warning: Invalid argument supplied for foreach() in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 19407
    Warning: array_push() expects parameter 1 to be array, null given in /Applications/AMPPS/www/tcpdf/tcpdf.php on line 16878

  • Wayne Sewell

    Never mind. I found the error. There was an extra that hosed everything. It didn’t show up above, because the prettyprinter that formatted the HTML fixed the error without telling me. The original was all one line, so prettyprint.

    It would have been nice for it to TELL me something was wrong with my HTML instead of doing weird things, but okay.

  • Wayne Sewell

    The editor ate the HTML code. There was an extra < / T R >

  • Wayne Sewell

    In hindsight, it all makes perfect sense. The unbalanced HTML caused all the warning messages about arrays, and those messages were the output that caused the total failure. It was complaining about the output it was generating itself.

    If you ever see warnings like that, check your HTML.

  • Lubos Dz

    Before sending HTML string to TCPDF you should send it to some pretty formater e.g. tidy — it would fix up invalid markups for you. Example:

    if(extension_loaded('tidy')){
        // http://tidy.sourceforge.net/docs/quickref.html
        $tidy = new tidy();
        $fixedHtml = $tidy->repairString($dirtyHtml, array(
            'output-xhtml' => true,
            'show-body-only' => true,
        ), 'utf8');
    }
    

     

    Last edit: Lubos Dz 2014-04-16

  • Wayne Sewell

    Thanks. That is fine if the HTML is coming from some external source, but if I am generating it, as in this case, I should be generating it correctly. The pretty formatting would be unnecessary overhead due to my own sloppiness. But I will keep that in mind for the former case.


Log in to post a comment.

Понравилась статья? Поделить с друзьями:
  • Tcp socket read operation failed error 64
  • Technical difficulties you have encountered a serious error zero hour
  • Tcp recv error connection reset by peer
  • Technical difficulties generals как исправить ошибку
  • Tcp provider error code 0x68 104