【问题标题】:Mozilla pdf.js, How to I specify the filename for download?Mozilla pdf.js,如何指定下载文件名?
【发布时间】:2014-08-18 20:57:14
【问题描述】:

我将包含以下代码的 php 文件的位置作为参数传递给 viewer.html 文件,它显示正确,但在 pdf 查看器中单击下载按钮时,文档名称始终为 document.pdf。这带来了一个问题,因为有多少移动用户在下载文件时才发现他们所有的文件都有名称document.pdf,并且他们(对于大多数移动浏览器)在下载之前无法更改文件名。

我是否必须将一些任意参数传递给文件或重定向到自身并附加文件名?

<?php
$content = "a binary representation of my pdf";
header("Content-type: application/pdf");
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="someFile.pdf"');
echo $content;
?>

【问题讨论】:

  • 去掉文件名周围的引号
  • 没有培根。结果相同。
  • 我唯一能想到的就是脱掉“附件;”
  • 也没有工作。感谢您的报价,但不知道
  • 我查看了一些代码,我想引号是否存在实际上并不重要,除非名称中有空格,就像 HTML 标记属性一样。

标签: php pdf.js


【解决方案1】:

我遇到了同样的问题。来自pdf.js的viewer.js源码:

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';
}

所以 majic 需要来自通过 reURI 正则表达式的 URL。

你需要做的是:

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

由于上面的正则表达式代码,每一个都将导致保存为Named.pdf 的文件名。

【讨论】:

  • 值得一提的是PDFViewerApplication有setTitleUsingUrl()。您可以使用它来指定下载的文件名。 PDFViewerApplication.setTitleUsingUrl('mypdf.com/the-pdf.pdf');
【解决方案2】:

基于 cmets

您可以将其添加到您使用 viewer.js 文件的任何位置。

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

然后,当您下载 PDF 时,它将具有该文件名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    相关资源
    最近更新 更多