Change language

How do I make a PDF downloadable from an HTML link using PHP?

|
Syntax:
  • http response headers for loading any application
    header ("Content-Type: application / octet-stream") ; 
  • HTTP response headers to set the composition and download file
    header (’Content-Disposition: attachment; filename =" downloaded.pdf "’) ; 
  • The length of the requested file needs to be downloaded
    header ("Content-Length:". filesize ("download.pdf")); 
  • Reads a file and writes it to the output buffer.
    readfile (’original.pdf’); 
  • , Note:Remember that the HTTP header() must be called before any actual output is sent, either with normal HTML tags, blank lines in a file, or from PHP.Example 1.Save the below HTML file as htmllinkpdf.html and save the PHP file as downloadpdf.php
    • Below is an example to illustrate the concept of downloading a PDF file using m HTML links.
    • Here the download is presented in PDF format, but without any content that shows an error when opened in any application
    • HTML code: < html > < head > < title > Download PDF using PHP from HTML Link < / title > < / head > < body > < center > < h2 style = "color: green;" > Welcome To GFG < / h2 > < p > < b > Click below to download PDF < / b > < / p > < a href = "gfgpdf.php? file = gfgpdf" > Download PDF Now < / a > < / center > < / body > < / html >
    • PHP Code: $file = $_ GET [ "file" ]. ". pdf" ;  
      // We will output the PDF header ( ’Content-Type: application / pdf’ );  
      // will be called download.pdf header ( ’Content-Disposition: attachment; filename =" gfgpdf.pdf "’ ); $imagpdf = file_put_contents ( $image , file_get_contents ( $file )); echo $imagepdf ; ?>
    • Output:
    Below is an example to illustrate the concept of downloading a PDF file locally (i.e. reading a gfgpdf.pdf file from a local file) using an HTML link.Example 2Save the HTML file as htmllinkpdf.html and save PHP file as downloadpdf.php file
    • HTML code: < html > < head > < title > Download PDF using PHP from HTML Link < / title > < / head > < body > < center > < h2 style = "color: green;" > Welcome To GFG < / h2 > < p > < b > Click below to download PDF < / b > < / p > < a href = "downloadpdf.php? file = gfgpdf" > Download PDF Now < / a > < / center > < / body > < / html >
    • PHP Code: 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 (); // It doesn’t matter. $fp = fopen ( $file , "r" ); while (! feof ( $fp )) { echo fread ( $fp , 65536); flush (); // This is important for large downloads} fclose ( $fp ); ?>
    • Output:
    SO 1 data error