呼び出し側
$pdf1 = file_get_contents('path/to/pdf1.pdf');
$pdf2 = file_get_contents('path/to/pdf2.pdf');
$pdf3 = file_get_contents('path/to/pdf3.pdf');
$merger = new \App\SomeDirectory\PDFMargeSample();
$mergedPdf = $merger->mergePdf([$pdf1, $pdf2, $pdf3]);
file_put_contents('path/to/merged.pdf', $mergedPdf);
マージ処理本体
<?php
namespace App\SomeDirectory;
use setasign\Fpdi\Tcpdf\Fpdi;
class PDFMargeSample
{
/**
* 複数のPDFデータを結合
*
* @param array $contentsArray PDFデータの配列(バイナリ文字列)
* @return string 結合されたPDFデータ(バイナリ文字列)
*/
public function mergePdf(array $contentsArray): string
{
if (empty($contentsArray)) {
throw new \InvalidArgumentException("PDFデータが空です。");
}
// FPDIのインスタンスを作成
$pdf = new Fpdi();
$pdf->setPrintHeader(false);
// 各PDFデータを順番に結合
foreach ($contentsArray as $contents) {
if (!is_string($contents)) {
throw new \InvalidArgumentException("PDFデータは文字列である必要があります。");
}
// PDFの内容を一時ファイルに格納
$tempFile = tmpfile();
fwrite($tempFile, $contents);
$tempPath = stream_get_meta_data($tempFile)['uri'];
// PDFをFPDIに追加
$pageCount = $pdf->setSourceFile($tempPath);
for ($i = 0; $i < $pageCount; $i++) {
$pdf->AddPage();
$pdf->useTemplate($pdf->importPage($i + 1));
}
// 一時ファイルを閉じる
fclose($tempFile);
}
// 結合されたPDFを出力
return $pdf->Output(null, 'S');
}
}