技术饭

php生成pdf文件上传到七牛云

copylian    0 评论    8576 浏览    2023.06.23

php生成pdf文件上传到七牛云,php生成pdf使用 composer require tecnickcom/tcpdf,通过html生成对应的pdf使用还是很方便的,缺点是html样式不是很好调整,七牛云上传使用七牛云提供的类库 composer require qiniu/php-sdk即。

php下有多个类库可以生成pdf如tcpdf、mpdf,但是html需要比较写得纯粹些,否则很多样式不支持,导致生成得pdf很乱。

mpdf:https://github.com/mpdf/mpdf、http://mpdf.github.io/

<?php

const QINIU_KEY= "b14aD6_O0jWU1D1-xxxxxx";

const QINIU_SECRET= "xxxxxx";

const QINIU_BUCKET= "xxxx";

const QINIU_HOST= "https://xxxx.com";


//html文件,变量替换成值

$html = file_get_contents("pdf.html");

$html = str_replace('${contractNo}', $value["serial_number"]."-HT", $html);

$html = str_replace('${signTime}', date("Y年m月d日",strtotime($history[Order::ACTION_DEAL])), $html);

$html = str_replace('${name}', $value["carrier"]["name"], $html);

$html = str_replace('${idCard}', $value["carrier"]["identity_card"]["number"], $html);

$html = str_replace('${mobile}', $value["carrier"]["phone_number"], $html);


//生成base64的png印章图片

$imgFile = $this->getSealImg($value["carrier"]["name"]."印");

$html = str_replace('${imgFile}', $imgFile, $html);


//生成pdf

$upFile = $this->getPdfFile($html, "名称", "文件名称", "S"); //PDF输出的方式。I,在浏览器中打开;D,以文件形式下载;F,保存到服务器中;S,以字符串形式输出;E:以邮件的附件输出。


//上传合同到七牛云:$upType:file-本地文件,stream-二进制流

$fileKey = $this->uploadFileToQiniu("stream", $upFile);

$res = $this->getFileUrl("/" . $fileKey);

$ownersContractFile = $res["headers"]["Location"];


/**

* 获取省份证的性别、生日

* @param $idNumber

* @return array

*/

private function getIdcarBirthSex($idNumber = ""){

        $birth = strlen($idNumber) == 15 ? ('19' . substr($idNumber, 6, 6)) : substr($idNumber, 6, 8);

        $birth = date("Y-m-d", strtotime($birth));

        $sex = ((int)substr($idNumber, (strlen($idNumber)==18 ? -2 : -1), 1)) % 2 ? '1' : '0'; //1为男 2为女

        return ['birth' => $birth, 'sex' => $sex];

}


/**

* 文件上传到七牛云

* @param $upType 文件上传类型

* @param $file

* @return mixed

* @throws \Exception

*/

private function uploadFileToQiniu($upType = "file", $file = ""){

        $ext = "pdf";

        if ($upType == "file") {

                $pathinfo = pathinfo($file);

                // 通过pathinfo函数获取图片后缀名

                $ext = $pathinfo['extension'];

        }


        // 构建鉴权对象

        $auth = new Auth(QINIU_KEY,QINIU_SECRET);

        

        // 生成上传需要的token

        $token = $auth->uploadToken(QINIU_BUCKET);


        // 上传到七牛后保存的文件名

        $filename = md5(date('Y').'/'.date('m').'/'.substr(md5($file),8,5).date('Ymd').rand(0,9999).".".$ext);

        

        // 初始化UploadManager类

        $uploadMgr = new UploadManager();

        if ($upType == "file") {

                [$res, $err] = $uploadMgr->putFile($token, $filename, $file, null, 'application/octet-stream', true, null, 'v2');

        } else {

                [$res, $err] = $uploadMgr->put($token, $filename, $file, null, 'application/octet-stream');

        }

        if($err !== null){

                throw new \Exception("文件上传错误");

        }

        return $res["key"];

}


/**

 * 获取七牛云文件地址

* @param $key

* @return string

*/

private function getQiniuile($key){

        // 构建鉴权对象

        $auth = new Auth(QINIU_KEY,QINIU_SECRET);

        // 私有空间中的外链 http://<domain>/<file_key>

         // 对链接进行签名

        $baseUrl = QINIU_DOMAIN.'/'.$key;

        //    print_r($baseUrl);

        return $auth->privateDownloadUrl($baseUrl);

}


/**

* 获取pdf文件

* @param $html

* @param $title

* @param $fileName

* @return void

*/

private function getPdfFile($html = '', $title = "合同", $fileName = "pdf", $showType = "F"){

        //实例化tcpdf

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

        

        // 设置打印模式

        //设置文件信息,头部的信息设置

        $pdf->SetCreator("云仓配");

        $pdf->SetAuthor("ycp");

        $pdf->SetTitle($title);

        $pdf->SetSubject($title);

        $pdf->SetKeywords($title);//设置关键字

        

        //是否显示页眉

        $pdf->setPrintHeader(false);

        //设置页眉显示的内容

        //  $pdf->SetHeaderData('logo.png', 60, 'owndraw.com', '', array(0,64,255), array(0,64,128));

        //设置页眉字体

        //  $pdf->setHeaderFont(Array('deja2vusans', '', '12'));

        

        //是否显示页脚

        $pdf->setPrintFooter(false);

        

        //页眉距离顶部的距离

        //  $pdf->SetHeaderMargin('5');

        

        //   设置页脚显示的内容

        //  $pdf->setFooterData(array(0,64,0), array(0,64,128));

        

        // 设置页脚的字体

        //  $pdf->setFooterFont(Array('dejavusans', '', '5'));

        

        // 设置页脚距离底部的距离

        //  $pdf->SetFooterMargin('5');

        

        // 设置默认等宽字体

        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        

        // 设置行高

        $pdf->setCellHeightRatio(1);

        

        // 设置左、上、右的间距

        $pdf->SetMargins('10', '5', '10');

        

        // 设置是否自动分页 距离底部多少距离时分页

        $pdf->SetAutoPageBreak(TRUE, '5');

        

        // 设置图像比例因子

        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        $pdf->setFontSubsetting(true);

        $pdf->AddPage("A4","Landscape",true,true);

        

        // 设置字体

        $pdf->SetFont('stsongstdlight', '', 10, '', true);

        $pdf->writeHTML($html);//HTML生成PDF

        //$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

        //      $showType= 'F'; //PDF输出的方式。I,在浏览器中打开;D,以文件形式下载;F,保存到服务器中;S,以字符串形式输出;E:以邮件的附件输出。

        //  ob_end_clean();

        $path = $_SERVER['DOCUMENT_ROOT'].'static/pdf/';

        //判断保存目录是否存在,不存在则进行创建

        if(!is_dir($path)){

                mkdir($path,'0777',true);

        }

        $file = $path."{$fileName}.pdf";

        //      file_put_contents($file,"");

        $pdfFile = $pdf->Output($file, $showType);

        if ($showType == 'F'){

                return $file;

        }

        return $pdfFile;

        //    $pdf->Output('./static/'.$fileName.'.pdf', 'F');

        //    return $pdf->Output('pdf.pdf', 'S');

}


/**

* 生成印章

* @param $name

* @return string

*/

private function getSealImg($name = ""){

        //在图像上写入文本

        //  $font = 'simsun.ttc';

        $font = './static/STZHONGS.TTF';

        $width = 120;

        $height = 120;

        $thickness = 2; //线条边框粗细

        $fontsize = 38; //字体大小

        

        //创建图像对象

        $image = imagecreatetruecolor($width, $height);

        

        //设置背景颜色和文本颜色

        $bg_color = imagecolorallocatealpha($image , 255 , 255 , 255, 127);

        $text_color = imagecolorallocate($image, 255, 0, 0); //文本颜色

        $rect_color = imagecolorallocate($image, 255, 0, 0); //边框红色

        //填充背景色

        imagefill($image, 0, 0, $bg_color);

        

        //设置透明

        //  imagecolortransparent($image, $bg_color);

        

        //边框粗细

        imagesetthickness($image, $thickness);

        

        //画一个矩形

        imagerectangle($image, 0, 1, $width - $thickness, $height - $thickness, $rect_color);

        

        //添加文本

        $nameArr = mb_str_split($name);

        $top = 15;

        $left = 10;

        

        //获取字体大小

        $box = imagettfbbox($fontsize, 0, $font, $nameArr[0]);

        $fontHeight = $box[3] - $box[5];

        $fontWidth = $box[4] - $box[6];

        

        //写入文字

        if(isset($nameArr[0])){

                imagettftext($image, $fontsize, 0, $width - $fontWidth - $left,$fontHeight, $text_color, $font, $nameArr[0]);

        }

        if(isset($nameArr[1])) {

                imagettftext($image, $fontsize, 0, $width - $fontWidth - $left, $height - $top, $text_color, $font, $nameArr[1]);

        }

        if(isset($nameArr[2])) {

                imagettftext($image, $fontsize, 0, $left-2, $fontHeight, $text_color, $font, $nameArr[2]);

        }

        if(isset($nameArr[3])) {

                imagettftext($image, $fontsize, 0, $left-2, $height - $top, $text_color, $font, $nameArr[3]);

        }

        

        //创建缓冲区

        ob_start();

        

        //保存图像

        imagepng($image);

        $buffer = ob_get_clean();

        //      ob_end_clean();

        $base64 = base64_encode($buffer);

        $imageData = 'data:'. "image/png" . ';base64,' . $base64;

        return $imageData;

}


参考:

https://www.kancloud.cn/ling-wei/test/1060095

https://developer.qiniu.com/kodo/1241/php#4

只袄早~~~
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!
php pdf 七牛云 tcpdf 

文明上网理性发言!

  • 还没有评论,沙发等你来抢