38

My scenario is that PDF file download automatically, then user fills it and when click on submit button in PDF it connect to java servlet and save it in DB.

  1. User click on Button
  2. JavaScript code run and PDF file download automatically
  3. open file using JavaScript automatically
  4. user fills & press submit
  5. after submit servlet code run and save data in db

In my Application just the 2nd point is missing. Please provide code how to interact with extension using JavaScript to download file automatically. I just want to download the file.

2
  • document.location = 'url of pdf' Commented Jan 9, 2016 at 8:54
  • 1
    Please be more specific. Do you just need an approach as @JaromandaX is showing above or be more specific on this. Commented Jan 9, 2016 at 9:30

7 Answers 7

88

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
Sign up to request clarification or add additional context in comments.

10 Comments

Thats Great Its Working.Thanks a lot.Can we specify the path where the file is to be downloaded ?? chrome does not ask for path and take path programetically using javascript or HTML
@EhsaanIsrar we cannot. Browsers normally use the user settings for downloaded files.
Thanks a lot. can you tell me how to download automatically in xhtml ??i am working on a java based framework liferay portlet in which views are designed using xhtml and primefaces ??is there any way to download automatically in this
not working on latest chrome and Ubuntu 18.04 in june 2020, could you please tell what needs to be changed if any? as downloaded file is showing Failed, No file error and can't open a file, and instead of createElement('a'), how can I give element-id of any div?
this doesn't work. this opens the PDF on latest chrome nov 2021
|
14

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);

2 Comments

this opening the pdf file in new window, is there any way to directly download?
this works too although the new window opens and closes immediately which results in not great UX
7
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function

Comments

3
// Define the URL of the PDF file
var pdfUrl = "http://example.com/path/to/your/pdf.pdf";

// Function to trigger the download
function downloadPdf() {
  fetch(pdfUrl)
    .then(response => response.blob())
    .then(blob => {
      // Create a blob URL for the PDF data
      var url = window.URL.createObjectURL(blob);

      // Create a link element to trigger the download
      var a = document.createElement("a");
      a.href = url;
      a.download = "downloaded.pdf"; // Set the desired file name
      document.body.appendChild(a);

      // Trigger a click event on the link element to initiate the download
      a.click();

      // Clean up by revoking the blob URL and removing the link element
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    })
    .catch(error => {
      console.error("Failed to download the PDF file: ", error);
    });
}

// Call the downloadPdf() function when needed, e.g., in response to a button click
document.getElementById("downloadButton").addEventListener("click", downloadPdf);
  1. Replace http://example.com/path/to/your/pdf.pdf with the actual URL of the PDF file you want to download.
  2. The fetch() function is used to make a GET request to the PDF file URL.
  3. Once the response is received, the PDF content is converted to a blob, and a blob URL is created.
  4. An anchor element () is dynamically created, and its href attribute is set to the blob URL. You can specify the desired file name using the download attribute.
  5. The anchor element is appended to the document's body.
  6. A click event is programmatically triggered on the anchor element to initiate the download.
  7. Finally, the blob URL is revoked, and the anchor element is removed from the document to clean up.

You can call the downloadPdf() function in response to a button click or any other user action to initiate the download.

Comments

1

Please try this

(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>

Or use download attribute to tag in HTML5

Comments

1

The other solutions didn't work for me in the latest chrome version, but the below code did

    const url = 'myurl.pdf';
    try {
        const response = await fetch(url);
        const blob = await response.blob();
        const downloadUrl = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = ''; // You can change the filename here
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        URL.revokeObjectURL(downloadUrl);
    } catch (error) {
        console.error('Error downloading the file', error);
    }

Comments

-3
  1. for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf

e.g. you're using php and $filepath contains pdf file path.

so you can write javascript like to to emulate download dialog box.

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';
</script

Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

7 Comments

i tried this :<script type="text/javascript"> window.location.href = 'file:///C:/Users/EHSAAN/Desktop/chrome%20extension/practice/abc.pdf'; </script> but it will open file not download it
window.location.href tells the url of file not download file
sorry, I meant to say below: should be fully qualified url to pdf file as shown below: <script type="text/javascript"> window.location.href = 'domain.com/files/filename.pdf' </script>
i give the complete path. i don't understand what you say ? Please Elaborate
Well, full path means if you enter direct url to pdf into browser address bar, you can access it. right? so that full url has to be there into $filepath variable of PHP.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.