HOWTO · PHP
PHP を使用して HTML 形式の PDF ファイルをダウンロードする
PHP を使用して HTML リンクで PDF ファイルをダウンロードできます。
このページの内容
このチュートリアルでは、PHP を使用して PDF ファイルを HTML リンクでダウンロード可能にする手順について説明します。 PHP の header() 関数を使用して、ユーザーに PDF ファイルを保存するよう促します。
PHP での header() 関数の構文
-
以下のヘッダーは、任意のアプリケーションをダウンロードします。
header("Content-Type: application/octet-stream"); -
以下のヘッダーは、構成とダウンロード可能なファイルを設定します。
header('Content-Disposition: attachment; filename="Delft.pdf"'); -
以下のヘッダーは、ファイルのサイズを示しています。
header("Content-Length: " . filesize("Delft.pdf"));
PHP を使用して HTML リンク付きの PDF をダウンロード
次の例では、PHP スクリプトを使用して HTML で PDF(Delft.pdf) をダウンロードしようとします。 Delft.pdf ファイルは空で、開くとエラーが表示されます。プロセスの進め方を写真で示します。
コード例 - HTML スクリプト:
<!DOCTYPE html>
<html>
<head>
<title>Download PDF using PHP from HTML Link</title>
</head>
<body>
<center>
<h2 style="color:red;">Welcome To DELFT</h2>
<p><b>Click below to download PDF</b></p>
<a href="downloadpdf.php?file=Delft">Download PDF Now</a>
</center>
</body>
</html>
コード例 - PHP スクリプト:
<?php
$file = $_GET["file"] .".pdf";
// To Output a PDF file
header('Content-Type: application/pdf');
// PDF will be called Delft.pdf
header('Content-Disposition: attachment; filename="Delft.pdf"');
$imagpdf = file_put_contents($image, file_get_contents($file));
echo $imagepdf;
?>
出力;
リンクは Delft.pdf ファイルをダウンロードしますが、ファイルが空であるため、開こうとするとエラーが発生します。 これが、PHP を使用して HTML リンクで PDF ファイルをダウンロードする基本的な概念です。
Delft.pdf ファイルをローカル マシンからダウンロードして読んでみましょう。 次の例では、HTML リンクを使用して PDF ファイルをローカルにダウンロードしようとします。
コード例 - HTML スクリプト:
<!DOCTYPE html>
<html>
<head>
<title>Download PDF using PHP from HTML Link</title>
</head>
<body>
<center>
<h2 style="color:blue;">Welcome To DELFTSTACK</h2>
<p><b>Click below to download PDF</b></p>
<a href="downloadpdf.php?file=Delft">Download PDF Now</a>
</center>
</body>
</html>
コード例 - PHP スクリプト:
<?php
header("Content-Type: application/octet-stream");
$file = $_GET["file"] . ".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // Not a must.
$fp = fopen($file, "r");
while (!feof($fp)) {
echo fread($fp, 65536);
flush(); // This is essential for large downloads
}
fclose($fp);
?>
出力;
リンクは Delft.pdf ファイルをダウンロードし、ファイルを正常に開きます。 出力を送信する前に、常にヘッダーを呼び出します。