chrome driver 로 pdf 다운로드 만들기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

php | chrome driver 로 pdf 다운로드 만들기

본문

php PDF 변환기 대부분의 라이브러리를 다 써봤는데 실제 화면과 pdf결과물이 너무 다르게 나온다.

그나마 낫다는 wkhtmltopdf 조차 flex 나 grid 등의 css가 잘 안먹힌다.

하지만 chrome driver 를 이용하면 화면과 거의 똑같이 출력이 가능하다.

이걸 모르고 괜히 몇일간 삽질했다 ㅜㅜ

 

centos7 에서 크롬드라이버를 설치한다.

 

1. 레포지토리 등록

[code]

$ vi /etc/yum.repos.d/google-chrome.repo

[/code]

 

[code] 

[google-chrome] 

name=google-chrome 

baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch 

enabled=1 

gpgcheck=1 

gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub 

[/code]

 

2. 설치

[code]

$ yum -y install google-chrome-stable

[/code]

 

3. 설치가 잘 되었는지 버전확인

[code]

$ google-chrome --version

[/code]

 

4. 실행해본다.

[code]

$ google-chrome --headless --print-to-pdf="./test.pdf" --no-sandbox http://google.com

[/code]

 

: test.pdf 가 다운로드 된다.

 

 

이제 php 에서 사용하기 위해 클래스 파일을 만든다.

: Html2Pdf.php

[code]

<?php

class Html2Pdf {

    private $html;

    private $filename;

    private $tmp_dir = '/tmp';

    private $binpath = '/usr/bin/google-chrome';

    private $url = '';

    

    public function setURL($url) {

        $this->url = $url;

    }

    

    public function setFilename($filename) {

        $this->filename = $filename;

    }

    

    public function setTempDir($dirpath) {

        $this->tmp_dir = rtrim($dirpath, '/');

    }

    

    public function setBinary($binpath) {

        $this->binpath = $binpath;

    }

    

    public function download() {

        $tmp_name = $this->tmp_dir.'/'.uniqid().'.pdf';

        

        shell_exec($this->binpath." --headless --print-to-pdf=\"".$tmp_name."\" --no-sandbox ".$this->url);

        

        header('Content-Type: application/pdf');

        header('Content-Disposition: attachment; filename="'.$this->filename.'"');


        if(preg_match("/msie/i", $_SERVER['HTTP_USER_AGENT']) && preg_match("/5\.5/", $_SERVER['HTTP_USER_AGENT'])) {

            header("content-type: doesn/matter");

            header("content-length: ".filesize($tmp_name));

            header("content-disposition: attachment; filename=\"".$this->filename."\"");

            header("content-transfer-encoding: binary");

        } else if (preg_match("/Firefox/i", $_SERVER['HTTP_USER_AGENT'])){

            header("content-type: file/unknown");

            header("content-length: ".filesize($tmp_name));

            header("content-disposition: attachment; filename=\"".basename($this->filename)."\"");

            header("content-description: php generated data");

        } else {

            header("content-type: file/unknown");

            header("content-length: ".filesize($tmp_name));

            header("content-disposition: attachment; filename=\"".$this->filename."\"");

            header("content-description: php generated data");

        }


        header("pragma: no-cache");

        header("expires: 0");

        flush();



        $download_rate = 10;


        $fp = fopen($tmp_name, 'rb');

        while(!feof($fp)) {

            print fread($fp, round($download_rate * 1024));

            flush();

            usleep(1000);

        }

        fclose ($fp);

        flush();


        unlink($tmp_name);

    }

}

[/code]

 

사용하기

[code]

include("Html2Pdf.php");

    

$hpdf = new Html2PDF();

$hpdf->setURL("http://google.com");

$hpdf->setFilename("test.pdf");

$hpdf->download();

[/code] 

 

 

※ 참고

PDF 페이지 설정

[code]

@page {

    size: A4;  // 종이 크기,  가로 세로를 직접 지정할 때는 1in 2in 와 같이 한다.

    margin: 1cm 0;

}

[/code]

 

테이블 줄바꿈 설정

[code]

@media print {

    /* 테이블 상위 element 는 block 이 되어야 한다. 중요!! */

    div.parent {

        display: block;

    }

    

    tr td{

        page-break-inside: avoid;  /* 테이블 줄바꿈을 하지 않고 다음페이지로 이어 연속으로 출력한다 */

        white-space: nowrap;

    }

[/code]

 

※ 만약 다운로드 받은 PDF의 한글이 깨질 경우 아래 패키지를 설치하면 된다. (우분투 기준)

[code]

sudo apt-get install fonts-unfonts-core

[/code]

 

댓글 0개

등록된 댓글이 없습니다.

Menu