网站首页 文章专栏 html转pdf、pdf转图片

html转pdf、pdf转图片

编辑时间:2020-06-17 16:53:13 作者:苹果 浏览量:2673


    前言:能用到html排版的文字,肯定结构比较复杂,一般需要能够下载或者打印,转成pdf最好,保存各种环境下排版不会错乱。 html无法直接生成图片,需要先生成pdf再转成图片。


html转pdf:

    安装组件包  mpdf  官方文档:http://mpdf.github.io/

    composer require  mpdf/mpdf    

    使用最下面pdfToImage类封装好的方法:

        $pdf=new pdfToImage();
        $pdf->css='CSS代码';
        $pdf->html='Html代码';
        $pdf->pdfUrl='生成的pdf路径地址';
        $pdf->makePdf();
        或者:
        $pdf=new pdfToImage('CSS代码','Html代码',生成的pdf路径地址);
        $pdf->makePdf();

pdf转png 图片:

    pdf转图片需要依赖php的 imagick  扩展以及 ghostscript、ImageMagick服务
    安装方法: 

         1.安装编译工具 yum install wget make gcc gcc-c++ gtk±devel zlib-devel openssl openssl-devel pcre-devel kernel keyutils patch perl
         2.ghostscript   官网 https://www.ghostscript.com/download.html    建议直接yum 安装,以避免少加载了某些字体库
         3.ImageMagick   官网 http://www.imagemagick.com.cn/download.html  yum安装或编译安装均可,以下是编译安装的方法:

           wget http://www.imagemagick.org/download/ImageMagick.tar.gz
            tar -zxvf ImageMagick.tar.gz
            cd ImageMagick-7.0.10-18/
            ./configure --prefix=/usr/local/imagemagick
            make
            make install
            export PKG_CONFIG_PATH=/usr/local/imagemagick/lib/pkgconfig


         4.imagick  官网 https://pecl.php.net/package/imagick      根据自己的php安装方法而选择是yum安装或者编译安装,以下是编译安装:

           wget https://pecl.php.net/get/imagick-3.4.4.tgz
            tar -xzvf  imagick-3.4.4.tgz
            cd  imagick-3.4.4.tgz/
             /usr/bin/phpize
            ./configure --with-php-config=/usr/local/php/bin/php-config --with-imagick=/usr/local/imagemagick
            make
            make install

            在php.ini 中添加 extension=imagick.so


    使用最下面pdfToImage类封装好的方法:

        $pdf=new pdfToImage();
        $pdf->pdf_url='pdf绝对路径地址';
        $pdf->pdfToImage('生成的图片要保存的路径');//注意,只是路径,返回的是图片地址集合


pdfToImage代码:


class pdfToImage
{

    
    public $css;
    public $html;
    public $pdf_url; //pdf地址
    public $water_image;//水印图片

        public function __construct($css,$html,$pdf_url)
        {
            $this->css = $css;
            $this->html = $html;
            $this->pdf_url = $pdf_url;
        }


        /**生成pdf 
         * @throws \Mpdf\MpdfException
         * @author: hbh
         * @Time: 2020/6/16   16:47
         */
        public function makePdf()
        {
            //pdf要存放的地址
            $fullPath = $this->filePathInfo($this->pdf_url, 'dirname');
            //如果文件夹不存在则创建
            if (!file_exists($fullPath)) {
                $this->createDirectory($fullPath, 0755);
            }
            $config = [
                'mode' => 'utf-8',
                'format' => 'A4',
                'default_font_size' => 0,
                'default_font' => '',
                'margin_left' => 15,
                'margin_right' => 15,
                'margin_top' => 16,
                'margin_bottom' => 16,
                'margin_header' => 9,
                'margin_footer' => 9,
                'orientation' => 'P',
                'tempDir' => 'tempDir',
            ];
            if (!file_exists($config['tempDir'])) {
                $this->createDirectory($config['tempDir'], 0777);
            }
            $mpdf = new \Mpdf\Mpdf($config);
            $mpdf->autoScriptToLang = true;//支持中文设置
            $mpdf->autoLangToFont = true;//支持中文设置
        
            $mpdf->SetDisplayMode('fullpage');//设置PDF显示方式
        
            $mpdf->WriteHTML($this->css, 1);
            $mpdf->showWatermarkText = true;
            $mpdf->WriteHTML($this->html);
            if ($this->water_image) {
                //使用图片水印
                $mpdf->SetWatermarkImage($this->water_image);
                $mpdf->showWatermarkImage = true;
            }
        
            //生成的pdf 仅仅可用做打印
            $mpdf->SetProtection(['print']);
            $mpdf->Output($this->pdf_url, 'f');//保存pdf文件到指定目录  d 下载  s 返回字符串
        
        }
        

    /**pdf 转图片
     * @param $pdf //pdf路径
     * @param $path //生成的图片路径
     * @return array
     * @throws ImagickException
     * @author: hbh
     * @Time: 2020/6/17   16:26
     */
    public function pdfToImage($path)
    {
        if (!extension_loaded('imagick')) {
            return false;
        }
        if (!file_exists($this->pdf_url)) {
            return false;
        }
        if (!file_exists($path)) {
            $this->createDirectory($path, 0755);
        }
        $image = new \Imagick();
        $image->setResolution(300, 300); //设置分辨率 值越大分辨率越高
        $image->setCompressionQuality(100);
        $image->setBackgroundColor('white');
        //生成一组图片
        $return = [];
        //解析pdf依赖于 ghostscript
        $image->readImage($this->pdf_url);
        foreach ($image as $k => $item) {
            $item->setImageFormat('png');
            $file_name = $path . '/' . ($k + 1) . '.png';
            //以pdf原底色为图片背景色
            $image->mergeImageLayers($image::LAYERMETHOD_FLATTEN);
            $image->setImageAlphaChannel($image::ALPHACHANNEL_REMOVE);
            if ($item->writeImage($file_name) == true) {
                $return[] = $file_name;
            }
        }
        return $return;

    }
     /**
         * 获取文件信息
         * @param $file_url //文件全路径
         * @param $param    //要获取的
         * @return bool
         */
    public function filePathInfo($file_url, $param = '')
        {
            $path_parts = array();
            $path_parts ['dirname'] = rtrim(substr($file_url, 0, strrpos($file_url, '/')), "/") . "/";
            $path_parts ['basename'] = ltrim(substr($file_url, strrpos($file_url, '/')), "/");
            $path_parts ['extension'] = substr(strrchr($file_url, '.'), 1);
            $path_parts ['filename'] = ltrim(substr($path_parts ['basename'], 0, strrpos($path_parts ['basename'], '.')), "/");
            return isset($path_parts[$param]) ? $path_parts[$param] : $path_parts;
        }
    
        /**
         * 创建目录
         * @param $dir
         * @param int $mode
         * @return bool
         */
        private function createDirectory($dir, $mode = 0777)
        {
            if (is_dir($dir) || @mkdir($dir, $mode)) {
                return true;
            }
            if (!mkdir(dirname($dir), $mode, true)) {
                return false;
            }
            return @mkdir($dir, $mode);
        }

}



    出自:何冰华个人网站

    地址:https://www.hebinghua.com/

    转载请注明出处


来说两句吧
最新评论