Skip to main content
All CollectionsSetup and IntegrationsAgent Installation
Making Documents with jQuery / JavaScript
Making Documents with jQuery / JavaScript
Jonathon Fruchte avatar
Written by Jonathon Fruchte
Updated over 3 years ago

Until all modern browsers support the download link attribute, the most bulletproof way to make an external request with JavaScript that triggers a file download is by constructing a form and submitting it. Here's some example code using that technique to convert dynamically generated HTML into a PDF, using jQuery:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript">
      // this function is based on code found:
      // http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
      // to easily make a form and POST it
      var download = function(url, data, method){
        //url and data options required
        if( url && data ){
          jQuery('<form style="display: none" id="dr_submission" action="' + url
                 + '" method="' + (method||'post') + '">'
                 + '</form>').appendTo('body');
          //credentials
          jQuery('form#dr_submission').append('<textarea name="user_credentials"></textarea>');
          jQuery('form#dr_submission textarea[name=user_credentials]').val(data.user_credentials);

          //doc values
          for(var key in data.doc) {
            jQuery('form#dr_submission').append('<textarea name="doc['+key+']"></textarea>');
            jQuery('form#dr_submission textarea[name="doc['+key+']"]').val(data.doc[key]);
          }

          //submit the form
          if(confirm("press ok")) {jQuery('form#dr_submission').submit().remove(); }
        };
      };

      // setup the string represeting the html we want to submit
      var content = 'This is a sample PDF created using jQuery. Find more examples of what you can do with DocRaptor <a href="https://docraptor.com/">https://docraptor.com/</a> or contact support@docraptor.com with any questions.';

      var data = {
        doc: {
          test: true,
          type: 'pdf',
          document_content: content
        },
        user_credentials: "YOUR_API_KEY_HERE"
      };

      var call_download = function() {
        // this drops a form on the page and submits, which will result in a download dialog popping up
        download("http://docraptor.com/docs", data);
      };
    </script>
  </head>
  <body>
    <input type="button" value="submit" onclick="call_download();" />
  </body>
</html>

We've got a DocRaptor jQuery plugin that you should check out. Examples and usage details can be found on that page.

Note: if you don't want to expose your API key in your client-side JavaScript, check out Referrer-based Document Generation. Also, DocRaptor fully supports the CORS specification, allowing cross-site HTTP requests.

Did this answer your question?