0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複数のPDFを結合するサンプル

Posted at

呼び出し側

$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');
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?