PHP를 사용하여 HTML로 PDF 파일 다운로드

John Wachira 2023년6월20일
  1. PHP에서 header() 함수의 구문
  2. PHP를 사용하여 HTML 링크로 PDF 다운로드
PHP를 사용하여 HTML로 PDF 파일 다운로드

이 자습서에서는 PHP를 사용하여 HTML 링크에서 PDF 파일을 다운로드할 수 있도록 만드는 단계에 대해 설명합니다. PHP header() 기능을 사용하여 사용자에게 PDF 파일을 저장하라는 메시지를 표시합니다.

PHP에서 header() 함수의 구문

  1. 아래 헤더는 모든 애플리케이션을 다운로드합니다.

    header("Content-Type: application/octet-stream");
    
  2. 아래 헤더는 구성 및 다운로드 가능한 파일을 설정합니다.

    header('Content-Disposition: attachment; filename="Delft.pdf"');
    
  3. 아래 헤더는 파일 크기를 나타냅니다.

    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;
?>

산출;

PHP 스크립트가 포함된 HTML 링크로 PDF 다운로드

PHP 스크립트 출력이 있는 HTML 링크의 PDF 다운로드

링크는 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);
?>

산출;

HTML 링크를 사용하여 로컬에서 PDF 파일 다운로드

HTML 링크 출력을 사용하여 로컬에서 PDF 파일 다운로드

링크는 Delft.pdf 파일을 다운로드하고 성공적으로 파일을 엽니다. 출력을 보내기 전에 항상 헤더를 호출하십시오.

작가: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn