使用TCPDF生成PDF下载

7
我无法生成PDF下载,以下是我的代码,请问有什么问题?
include 'tcpdf.php';
$pdf = new TCPDF();
$pdf->AddPage('P', 'A4');
$html = '<html>
<head></head>
<body><table border="1">
<tr><th>name</th>
<th>company</th></tr>
<tr>
<td>hello</td>
<td>xx technologies</td>
</tr>
</table>
</body>
</html>';

$pdf->writeHTML($html, true, false, true, false, '');

$pdf->Output();
?>

你有 PHP 报告的任何错误吗? - netvision73
3个回答

7

我已经修改了你的代码,现在它可以正常运行。[测试通过]

<?php
require_once('tcpdf_include.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 9);
$pdf->AddPage();
$html = '<html>
<head></head>
<body><table border="1">
<tr><th>name</th>
<th>company</th></tr>
<tr>
<td>hello</td>
<td>xx technologies</td>
</tr>
</table>
</body>
</html>';
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output('htmlout.pdf', 'I');
?>

输出:

在此输入图片描述


嗨,Shankar,我仍然没有得到输出。 - namratha
嗨Namratha,它正常工作。你能描述一下错误吗?你的tcpdf库是否被正确引用? - Shankar Narayana Damodaran
我正在尝试做这件事,但它显示TCPDF类未找到,但我已经添加了所有文件。 - user3099225

4
如果你想要进行文件下载,需要在$pdf->Output();之前使用PHP函数header,如下所示:
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
$pdf->Output(); # terminate your file with TCPDF output

请查看php.net中有关PHP函数header的说明。


6
完全不对,这个答案是错误的。TCPDF类本身提供方法,只需将此参数传递给Output方法: $pdf->Output('yourfilename.pdf', 'D'); 就是这样。 - f.arcarese

2

请将$pdf->Output();替换为$pdf->Output($downlaodname, 'D');,这样就可以强制浏览器下载文件了。


这个答案在Chrome和我的环境下有效。 - user1882752

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接