来源:https://blog.csdn.net/qq_23564667/article/details/107524645
在做项目中,由于使用的是thinkphp5.1框架,使用tcpdf生成的pdf文件在浏览器里显示输出文件流字符串;
这个问题只要:关闭调试模式即可
1、通过Composer下载最新版TCPDF,切换到程序根目录运行如下命令:
composer require tecnickcom/tcpdf
命令成功执行后,TCPDF会被下载到程序根目录中的vendor文件夹,如图:
examples中有60多个典型示例,需要什么功能直接看例子即可,例子对应列表见TCPDF官网:https://tcpdf.org/examples/
2.在控制器中调用TCPDF。
function get_pdf_test(){ $html = <<<EOD <h1>hello word 你好啊</h1> EOD; //新建一个PDF文档 //L 横排 P竖排 $orientation='P'; $unit='mm'; $format='A4'; $unicode=true; $encoding='UTF-8'; $diskcache=false; $pdfa=false; $pdf = new \TCPDF($orientation, $unit, $format, $unicode, $encoding, $diskcache, $pdfa); $pdf->AddPage(); $pdf->SetFont('stsongstdlight', '', 14); // 使用中文字体,不设置这个,中文就会乱码 //如果要对html指定 宽度 writeHTMLCell更方便 $pdf->writeHTMLCell(0, 0, 0, 0, $html, 0, 0, 0, true, '', true); //直接输入到浏览器 //PDF输出 I:在浏览器中打开,D:下载,F:在服务器生成pdf ,S:只返回pdf的字符串 $pdf->Output('demo.pdf', 'I'); }
效果
3、中文乱码的问题
$pdf->SetFont('stsongstdlight', '', 14); // 使用中文字体,不设置这个,中文就会乱码
4、TCPDF不能保存中文文件名的解决方法
打开tcpdf.php文件,找到output函数,大约在7554行。
1、注释以下代码,大约在7565-7568行:
if ($dest[0] != 'F') { $name = preg_replace('/[\s]+/', '_', $name); $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name); }
2、搜索该方法代码,替换如下代码
header('Content-Disposition: attachment; filename="'.basename($name).'"');
替换为
header('Content-Disposition: attachment; filename="'.($name).'"');