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 <<
php-wkhtmltoxサンプル
php-wkhtmltoxサンプル
- HTMLをPDFへ変換します。対象URLを指定して下さい。
{$options['message']}