
PDF帳票のコーディング編
先日のインストール編からの続き
サーバにLibreOfficeをインストールすることで、エクセルのテンプレートを使い、PDFでの出力が可能となります。
エクセル出力の場合、
// ブラウザへの指定
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="yshu'.date("Y-m-d").'.xlsx"');
header('Cache-Control: max-age=0');
// XLSX形式で出力
$objWriter = new Xlsx($spreadsheet);
$objWriter->save('php://output'); PDF出力の場合、
一旦エクセルファイルを作成、これをPDFに変換となります。
// ==========================================
// 変換・出力処理(一時フォルダ利用)
// ==========================================
$workDir = sys_get_temp_dir();
$uniqueId = uniqid('yshu_', true);
$excelPath = $workDir . '/' . $uniqueId . '.xlsx';
$pdfPath = $workDir . '/' . $uniqueId . '.pdf';
// ① Excelファイルの保存
$writer = new Xlsx($spreadsheet);
$writer->save($excelPath);
// ② LibreOfficeによるPDFへの変換
$command = "libreoffice --headless --convert-to pdf " . escapeshellarg($excelPath) . " --outdir " . escapeshellarg($workDir) . " 2>&1";
exec($command, $output, $return_var);
// PDFが生成されなかった場合のガード
if (!file_exists($pdfPath)) {
echo "<h3>PDF変換エラー</h3>";
echo "Excelファイルの一時保存には成功しましたが、LibreOfficeでのPDF変換に失敗しました。<br>";
echo "<strong>コマンド実行結果:</strong><br><pre>" . implode("\n", $output) . "</pre>";
if (file_exists($excelPath)) { unlink($excelPath); }
exit;
}
// ③ PDFファイルをブラウザへ出力
if (ob_get_length()) { ob_end_clean(); }
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="yshu_' . date("Y-m-d") . '.pdf"');
header('Content-Length: ' . filesize($pdfPath));
header('Cache-Control: max-age=0');
readfile($pdfPath);
// ④ サーバー上の一時ファイルを削除
if (file_exists($excelPath)) { unlink($excelPath); }
if (file_exists($pdfPath)) { unlink($pdfPath); }全体コード
SQL部分は省略してあります。
利用のテーブルやフィールドに合わせて記述が必要になります。
file_type が、excel か pdf かで出力を2通りに出来るようにしてあります。
<?php
/*
サンプル
*/
// デバッグ用:エラーを画面に強制表示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
use PhpOffice\PhpSpreadsheet\Style\Border;
// ライブラリ読込
require '../excel/vendor/autoload.php';
// テンプレート読込
$reader = new XlsxReader();
$spreadsheet = $reader->load('form/template.xlsx');
// POSTデータの安全な受け取りと初期設定
$money = $_POST['money'] ?? "円";
// SQL処理
$sql = "SELECT pay_type1,pay_type2,pay_type3 ... FROM `table`... ";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$dt = $stmt->fetchAll(PDO::FETCH_ASSOC);
//シートをアクティブ設定
$spreadsheet->setActiveSheetIndex(0);
#タイトル表示(文字化け・波ダッシュ対策済)
$u8_yyy = mb_convert_encoding($yyy, "UTF-8", $current_encoding);
$u8_money = mb_convert_encoding($money, "UTF-8", $current_encoding);
$objSheet->setCellValue('C3', $u8_yyy);
$objSheet->setCellValue('I3', $u8_money);
// 書き込み
$tar = 6;
$count = count($dt);
//ループ処理
for ($i = 0; $i < $count; $i++) {
$objSheet->setCellValue('G'.$tar, $dt[$i]['pay_type1']);
$objSheet->setCellValue('H'.$tar, $dt[$i]['pay_type2']);
$objSheet->setCellValue('I'.$tar, $dt[$i]['pay_type3']);
}
$tar++;
}
# 印刷範囲指定
$objSheet->getPageSetup()->setPrintArea('A1:R'.$tar);
# 横幅を必ず1ページに収める設定
$objSheet->getPageSetup()->setFitToPage(true);
$objSheet->getPageSetup()->setFitToWidth(1);
$objSheet->getPageSetup()->setFitToHeight(0);
//エクセルの場合
if($file_tp === "excel"){
// ブラウザへの指定
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="yshu'.date("Y-m-d").'.xlsx"');
header('Cache-Control: max-age=0');
// XLSX形式で出力
$objWriter = new Xlsx($spreadsheet);
$objWriter->save('php://output');
}
//PDFの場合、
elseif($file_tp === "pdf"){
// ==========================================
// 変換・出力処理(一時フォルダ利用)
// ==========================================
$workDir = sys_get_temp_dir();
$uniqueId = uniqid('yshu_', true);
$excelPath = $workDir . '/' . $uniqueId . '.xlsx';
$pdfPath = $workDir . '/' . $uniqueId . '.pdf';
// ① Excelファイルの保存
$writer = new Xlsx($spreadsheet);
$writer->save($excelPath);
// ② LibreOfficeによるPDFへの変換
$command = "libreoffice --headless --convert-to pdf " . escapeshellarg($excelPath) . " --outdir " . escapeshellarg($workDir) . " 2>&1";
exec($command, $output, $return_var);
// PDFが生成されなかった場合のガード
if (!file_exists($pdfPath)) {
echo "<h3>PDF変換エラー</h3>";
echo "Excelファイルの一時保存には成功しましたが、LibreOfficeでのPDF変換に失敗しました。<br>";
echo "<strong>コマンド実行結果:</strong><br><pre>" . implode("\n", $output) . "</pre>";
if (file_exists($excelPath)) { unlink($excelPath); }
exit;
}
// ③ PDFファイルをブラウザへ出力
if (ob_get_length()) { ob_end_clean(); }
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="yshu_' . date("Y-m-d") . '.pdf"');
header('Content-Length: ' . filesize($pdfPath));
header('Cache-Control: max-age=0');
readfile($pdfPath);
// ④ サーバー上の一時ファイルを削除
if (file_exists($excelPath)) { unlink($excelPath); }
if (file_exists($pdfPath)) { unlink($pdfPath); }
}
exit;
?>