<?php
/*
 * 既存 PDF にタイムスタンプ付き署名を付与:
 * 既存の PDF 文書にタイムスタンプ付き署名を行うサンプルです。
 *
 * 必要な製品 : PDFlib PLOP DS 5
 * 必要なデータ : demo_signer_rsa_2048.p12
 *                  demo_signer_rsa_2048.p12 は data ディレクトリにあります。
 *                  demo_signer_rsa_2048.p12 のパスワードは demo です。 
 *                RFC3161 に対応したタイムスタンプサーバー
 *                  このサンプルでは https://www.infotek.co.jp/tsa を使用します。
 */


try {
    /* PLOP オブジェクトを生成する */
    $plop = new PLOP();

    /* 文書タイムスタンプのための署名オプション */
    $sign_opts =
        "engine=builtin ".
        "digitalid={filename={demo_signer_rsa_2048.p12}} ".
        "password={demo} ".
        "timestamp={source={ ".
        "  url={https://www.infotek.co.jp/tsa} ".
        "  sslverifypeer=false ".
        "}} ";

    /* 既存 PDF に関する変数を用意する */
    $searchpath = "../data";
    $infile = "PLOP-datasheet.pdf";
    $outfile = "";

    /* 読み込みたいファイルの入ったディレクトリを指定する */
    $optlist = sprintf("searchpath={%s}", $searchpath);
    $plop->set_option($optlist);

    /* ①既存の PDF 文書を開く */
    if (($doc = $plop->open_document($infile, "")) == 0) {
        die("Error: " . $plop->get_apiname() . ": " . $plop->get_errmsg() . "\n");
    }

    /* ②タイムスタンプ付き署名を作成する */
    if ($plop->prepare_signature($sign_opts) == 0) {
        die("Error: " . $plop->get_apiname() . ": " . $plop->get_errmsg() . "\n");
    }

    /* ③タイムスタンプ付き署名を PDF に付与して出力する */
    if ($plop->create_document($outfile, "input=". $doc) == 0) {
        die("Error: " . $plop->get_apiname() . ": " . $plop->get_errmsg() . "\n");
    }

    /* 生成した PDF をダウンロードさせる */
    $buf = $plop->get_buffer();
    $len = strlen($buf);
    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=certtimestamp.pdf");
    print $buf;

    /* ④PDF文書を閉じる */
    $plop->close_document($doc, "");

}
catch (PLOPException $e) {
    die("PLOP exception occurred in certtimestamp sample:\n" . "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " . $e->get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}

$plop = 0;