温馨提示×

wkhtmltopdf在PHP中的安装与使用方法

PHP
小樊
120
2024-08-09 21:51:40
栏目: 编程语言

要在PHP中使用wkhtmltopdf,需要先安装wkhtmltopdf软件。以下是在Linux系统中安装wkhtmltopdf的步骤:

  1. 下载wkhtmltopdf软件:
wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.bionic_amd64.deb
  1. 安装wkhtmltopdf软件:
sudo dpkg -i wkhtmltox_0.12.6-1.bionic_amd64.deb

安装完成后,可以在终端中输入wkhtmltopdf -V来检查是否安装成功。

接下来,可以使用PHP的exec()函数来调用wkhtmltopdf生成PDF文件。以下是一个简单的例子:

$html = '<html><head><title>Test</title></head><body><h1>Hello, World!</h1></body></html>';
$output_file = 'output.pdf';

$cmd = 'wkhtmltopdf -q -O Portrait -s A4 -L 10 -R 10 -T 10 -B 10 - ' . escapeshellarg($output_file);
$descriptorspec = array(
  0 => array("pipe", "r"),  // stdin
  1 => array("pipe", "w"),  // stdout
  2 => array("pipe", "w")   // stderr
);

$process = proc_open($cmd, $descriptorspec, $pipes, null, null);

if (is_resource($process)) {
  fwrite($pipes[0], $html);
  fclose($pipes[0]);

  $pdf = stream_get_contents($pipes[1]);
  fclose($pipes[1]);

  $error = stream_get_contents($pipes[2]);
  fclose($pipes[2]);

  $return_value = proc_close($process);

  if ($return_value === 0) {
    echo 'PDF file generated successfully.';
  } else {
    echo 'An error occurred: ' . $error;
  }
}

以上代码将生成一个简单的HTML内容并将其转换为PDF文件。可以根据自己的需求修改HTML内容和输出文件路径。要注意的是,wkhtmltopdf命令的参数可以根据需要进行调整。

希望这个信息对你有所帮助。

0