proc_openを用いることで生成されるPDFを標準入出力のパイプ処理によってメモリ上のみで処理する事ができます。
これによって、例えばtmpフォルダに保存しなくて良いので実行速度の向上、ハードディスクの容量を圧迫することの阻止ができます。
以下がそのコードです。
全体の概要としては、
1.PDFにしたいページのURLからHTMLを取得して標準入力に入れる
2.標準出力へそのHTMLを変換したPDFを出す。
3.変換したPDFをブラウザでダウンロードする
という流れになっています。
function generate_pdf()
{
$descriptorspec = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w'), // stderr
);
//get HTML from URL
$html =file_get_contents($site_url);
//execute wkhtmltopdf
$process = proc_open("wkhtmltopdf --q - -", $descriptorspec, $pipes);
// Send the HTML on stdin
fwrite($pipes[0], $html);
fclose($pipes[0]);
// Read the outputs
$pdf = stream_get_contents($pipes[1]);
fclose($pipes[1]);
//close process
$return_value = proc_close($process);
// Output the results
header('Content-Type: application/pdf');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename="paper.pdf";');
echo $pdf;
}
$site_urlに適切なURLを入力すればPDFを出力してくれます。HTTPヘッダとwkhtmltopdfのオプションはお好みで変えてください。


