利用wkhtmltopdf和PHP将HTML存成PDF

jopen 10年前

在PHP中生成PDF文件,可以使用 FPDFTCPDF 。但是它们只能用于创建简单的表格,当涉及到需要将图像添加到表中,就无法产生所需的布局。有一个强大的工具叫wkhtmltopdf就能够实现。

Wkhtmltopdf 是一个shell工具,它使用了WebKit渲染引擎和QT,将HTML转换为PDF格式。

安装wkhtmltopdf

# apt-get install wkhtmltopdf

从HTML生成PDF文件的基本语法如下:

# wkhtmltopdf input-file output-file

我们可以从任何网页生成PDF:

# wkhtmltopdf example.com example.pdf

或从本地html文件:

# wkhtmltopdf example.html example.pdf

以上命令只能在Linux box 图形环境中使用。如果我们在一个VPS或专用服务器上生成PDF,如果我们执行该命令,我们将得到从下错误:

wkhtmltopdf: cannot connect to X server

为了解决这个问题,我们需要使用一个名为 xvfb 的工具。

Xvfb是一个 X 服务器,能够运行在没有显示硬件和没有物理输入设备的机器上。它使用虚拟内存来模拟一个dumb framebuffer。

安装 xvfb

# apt-get install xvfb

接下来,我们需要创建一个shell脚本:

xvfb-run --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf $*

然后将它保存在 /usr/bin/wkhtmltopdf.sh 下

下一步,我们将创建一个 symbolic 链接,这样我们就可以执行脚本而不用编写的完整路径:

# ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf2

让我们尝试执行shell脚本,并看看会发生什么。

# wkhtmltopdf2 example.com example.pdf  Loading page (1/2)  Printing pages (2/2)                                                 Done

好,如果能够正确运行。就可以用以下自定义PHP脚本来生成一个PDF文件。

//Turn on output buffering  ob_start();    echo "<html>";  echo "<head>";  echo "<link href='http://example.com/style.css' rel='stylesheet' type='text/css'>";  echo "</head>";  echo "<body>";  echo "<p>custom HTML to PDF report</p>";  echo "</body>";  echo "</html>";    //return the contents of the output buffer  $html = ob_get_contents();  $filename = date('YmdHis');    //save the html page in tmp folder  file_put_contents("/tmp/{$filename}.html", $html);    //Clean the output buffer and turn off output buffering  ob_end_clean();     //convert HTML to PDF  shell_exec("wkhtmltopdf2 -q /tmp/{$filename}.html /tmp/{$filename}.pdf");  if(file_exists("/tmp/{$filename}.pdf")){   header("Content-type:application/pdf");   header("Content-Disposition:attachment;filename='{$filename}.pdf'");   echo file_get_contents("/tmp/{$filename}.pdf");  }else{   exit;  }