Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #1410396

    Hi, I’m using the button element for a downloadable PDF that currently opens in a new browser window. I’m wanting to have the PDF download to the users PC rather than having it open in a browser window. Is that possible and if so how do I go about doing this.

    Thanks

    #1410411

    Hey Snerp,

    Thank you for the inquiry.

    You may need to manually create a download link using the “a” tag and add the “download” attribute to it.

    // https://www.w3schools.com/tags/att_a_download.asp

    Best regards,
    Ismael

    #1410418

    Unfortunately, this is not a matter that you can control yourself. Even if the pdf links have this download attribute, the browser settings determine what happens – you can force a download – but the pdf file will open anyway in the browser.

    // with file-extension
    function force_pdf_link_to_download() { 
    ?>
    <script type="text/javascript">
    window.addEventListener("DOMContentLoaded", function () { 
    (function($){
          $('a[href$=".pdf"]').each(function() {
             pdfName = $(this).attr('href').match(/\/([^\/?#]+)[^\/]*$/)[1];
             $(this).attr('download', pdfName ).attr('target', '_blank'); 
          });
    })(jQuery);
    });   
    </script>
    <?php 
    }
    add_action('wp_footer', 'force_pdf_link_to_download');

    it is not possible to add a download attribute to a link with no value – even if you try that –
    texteditor will correct it to: download="" so the script above will insert download="filename.pdf"

    Even an entry in the htaccess file does not have to be followed by the browser:

    <FilesMatch "\.(?i:pdf)$">
    ForceType application/octet-stream
    Header set Content-Disposition attachment
    </FilesMatch>

    so what could be reached is that the file downloads on click – but it will open in browser tab too.

    Perhaps a more skilled programmer than me can force this behaviour – but I think it will be futile, especially since it is supposed to be browser independent.

    #1410610

    Ok, thank for the excellent support :)

    #1410634

    Hi,

    Thanks for the update and kind words :-)

    Please let us know if you should need any further help on the topic, or if we can close it.

    Best regards,
    Rikard

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.