Search code examples
javascriptphpdownloaddompdfhtml-to-pdf

pdf download using php and onclick function


I have the following code.

     <div onClick="registerationform.pdf">something</div>
     <?php
     header('Content-disposition: attachment; filename=registerationform.pdf');
     header('Content-type: application/pdf');
     readfile('registerationform.pdf');

This code directly downloads the output if the page is loaded. But I need the pdf to get downloaded only if the something button is clicked.Help me


Solution

  • Php code is executed before any page content is shown or any javascript is executed, and not exactly sequentially as you see it in your example.

    What you want is probably to create another php page downloadpdf.php which includes those headers you specified, and redirect the user to that page through a link:

    link.php:

    <a href="downloadpdf.php" target="_blank"> Download PDF </a>
    

    Note: target="_blank" is added here so the actual page is not redirected but instead the new page is opened in a new tab-> the browser downloads the file and immediately closes the tab, "feeling" like it's an immediate download from the current page you are on.

    downloadpdf.php

     <?php
     header('Content-disposition: attachment; filename=registerationform.pdf');
     header('Content-type: application/pdf');
     readfile('registerationform.pdf');