<?php
/**
* @file
* @brief php-wkhtmltox を用いたHTML -> PDF変換サンプル
* @author dexdev@gmail.com
* @version $Revision$
* @date $Date$
*/

error_reporting(E_ALL ^ E_NOTICE);
set_time_limit( 60 * 1 ); // 1分実行
mb_internal_encoding('utf-8');
mb_http_input('pass');
mb_http_output('pass');

exit(main($argc, $argv));

function main($argc, $argv)
{
	$html_options = array(
		'message' => '',
	);
	$url = $_POST['url'] = trim($_POST['url']);

	if(preg_match('/^(https?)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)$/', $url)){
		$result = convert($url, $_POST['format']);
		if(!$result){
			$html_options['message'] = 'HTML変換に失敗しました。';
		}
	}else if($url == ''){
	}else{
		$html_options['message'] = 'URLの形式が間違っています。';
	}
	
	html($html_options);
	
	return 0;
}

function convert($url, $format)
{
	$format = ($format == 'pdf') ? 'pdf' : 'image';
	$ext = ($format == 'pdf') ? 'pdf' : 'jpg';
	$tmpfname = tempnam("/tmp", "php-wkhtmltox");
	rename($tmpfname, $tmpfname . '.' . $ext);
	$tmpfname = $tmpfname . '.' . $ext;
	$filename = sprintf("%s.%s", date('YmdHis'), $ext);

	$result = false;
	switch($format){
	case 'pdf':
		$result = wkhtmltox_convert($format
			, array('out' => $tmpfname) // global settings
			, array(array('page' => $url))
			); // object settings
		break;
	case 'image':
		$result = wkhtmltox_convert($format, 
			array('out' => $tmpfname, 'in' => $url)); // global settings
		break;
	}
	
	if($result) download($tmpfname, $filename);
	
	return $result;
}

function download($tmpfname, $filename)
{
	header("Cache-Control: no-store, no-cache");
	header("Content-Type: application/octet-stream");
	header("Content-Disposition: attachment; filename={$filename}");

	$rfp = fopen($tmpfname,'rb');
	if(!$rfp) return false;
	
	while (!feof($rfp)) {
		echo fread($rfp, 8192);
	}
	fclose($rfp);
	exit(0);
}

function html($options=array())
{
	echo <<<EOD
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>php-wkhtmltoxサンプル</title>
	<style type="text/css">
	</style>
</head>
<body>

<h1>php-wkhtmltoxサンプル</h1>

<ul>
	<li>HTMLをPDFへ変換します。対象URLを指定して下さい。</li>
</ul>

<span style="font-weight:bold">{$options['message']}</span>

<form name="form1" id="form1" action="{$_SERVER['PHP_SELF']}" method="post">

URL：<input name="url" id="url" type="text" size="50" value="{$_POST['url']}" />
<input type="submit" value="変換" />
<br />
<fieldset style="width:600;">
	<legend>オプション</legend>
	<input type="radio" name="format" value="pdf" checked />PDF
	<input type="radio" name="format" value="image" />JPG
</fieldset>
</form>

</body>
</html>
EOD;
}
