1、首先 项目根目录运行 composer require tecnickcom/tcpdf 生成tcpdf库。 Composer中国镜像比较慢,这里推荐使用阿里云镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
2、在控制器里进行使用
<?php
namespace app\index\controller;
use think\facade\Config;
use think\Controller;
use think\Model;
use think\facade\Env;
use TCPDF;
class Question extends Controller
{
//生成pdf文件
public function paperWord($paper_id, $user_id, $type = 1)
{
$url = 'uploads/paper/' . randomFileName() . ".pdf";
// 生成PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(15, 15, 15);
$pdf->SetFont('stsongstdlight', '', 12);
$pdf->AddPage();
$pdf->writeHTML($content, true, false, true, false, '');
$rootPath = Env::get('root_path');
$showType= 'F';//PDF输出的方式。I,在浏览器中打开;D,以文件形式下载;F,保存到服务器中;S,以字符串形式输出;E:以邮件的附件输出
$filePath = $rootPath . 'public/' . $url;
$pdf->Output($filePath, $showType);
}
}
本文介绍如何在项目中利用TCPDF库通过Composer安装并配置阿里云镜像加速,实现在控制器内生成并保存PDF文件的功能。

2105

被折叠的 条评论
为什么被折叠?



