2
0

More than 1 year has passed since last update.

php から pdf をページとして表示する

Posted at

「LibreOffice で MySQL連動 PDF帳票を作る」
https://qiita.com/nanbuwks/items/d4696542760cf4b8a24a

ではスクリプトで pdf を作成しましたが、それの Webブラウザでのビューは iframe で行ってきました。

mkpreview.php

<!DOCTYPE HTML><HTML><HEAD><META CHARSET=UTF-8>
<TITLE></TITLE> <link rel="stylesheet" href="style.css"></HEAD><BODY>
<?php
$templatename= $_GET["use"];
$key= $_GET["key"];
exec("./mkpreview.sh ". $templatename."テンプレート.ods ".$key);
?>
<iframe src="<?php echo ($templatename); ?>テンプレート.ods.pdf#toolbar=0&view=FitV" name="sample" width="100%" height="700">
</iframe>
</BODY></HTML>

これをブラウザで以下のURLで呼び出すと、

http(s)://(servername)/(path)/mkpreview.php?use=紹介状&key=21

スクリプトで 「紹介状テンプレート.ods」 に key=21 の RDBMS データが反映されてた pdf が作成され、それが iframe で表示されます。

しかしながら、pdf だけ表示するのであれば iframe を使わずにブラウザに直接 pdf を送り込むのが都合がいいです。

環境

サーバ

  • Ubuntu 22.04
  • Apache/2.4.52 (Ubuntu)
  • php 8.1.2-1ubuntu2.11
    ブラウザ
  • google chrome 112.0.5615.138

コード

<?php
header('Content-Type: application/pdf');

$templatename= $_GET["use"];
$key= $_GET["key"];
exec("./mkpreview.sh ". $templatename."テンプレート.ods ".$key);

$filepath = $templatename."テンプレート.ods.pdf";
$filename = $templatename."テンプレート.ods.pdf";
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);

?>

これをブラウザで以下のURLで呼び出します。

http(s)://(servername)/(path)/mkpreview.php?use=紹介状&key=21

ブラウザでは、以下のように表示されます。

image.png

通常の pdf はこれでいいですが、今回はプレビューとしての表示なのでダウンロードや印刷は抑止したいです。ツールバーの表示を防ぐには、ブラウザから見る URL を以下のようにします。

http://(servername)/(path)/mkpreview.php?use=紹介状&key=21#toolbar=0&view=FitV

以下のように表示されます。

image.png

2
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
2
0