Mozilla pdf.js, How to I specify the filename for download?

I've run into this same issue. From the pdf.js's viewer.js source:

function getPDFFileNameFromURL(url) {
  var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  //            SCHEME      HOST         1.PATH  2.QUERY   3.REF
  // Pattern to get last matching NAME.pdf
  var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  var splitURI = reURI.exec(url);
  var suggestedFilename = reFilename.exec(splitURI[1]) ||
                           reFilename.exec(splitURI[2]) ||
                           reFilename.exec(splitURI[3]);
  if (suggestedFilename) {
    suggestedFilename = suggestedFilename[0];
    if (suggestedFilename.indexOf('%') != -1) {
      // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
      try {
        suggestedFilename =
          reFilename.exec(decodeURIComponent(suggestedFilename))[0];
      } catch(e) { // Possible (extremely rare) errors:
        // URIError "Malformed URI", e.g. for "%AA.pdf"
        // TypeError "null has no properties", e.g. for "%2F.pdf"
      }
    }
  }
  return suggestedFilename || 'document.pdf';
}

So the majic needs to come from the URL via the reURI regexp.

What you need to do is this:

http://domain.com/path/to/Named.pdf
http://domain.com/path/to/your/api?fileId=123&saveName=Named.pdf

Each of these will result in a save as filename of Named.pdf thanks to the regexp code above.


Based on comments

You can add this to wherever you're using the viewer.js file.

setTimeout(() => {
  // Wait for PDFViewerApplication object to exist
  PDFViewerApplication.setTitleUsingUrl('custom-file.pdf');
}, 10);

Then when you download the PDF it will have that filename

Tags:

Php

Pdf.Js