如何在不打开浏览器的情况下下载pdf文件

时间:2016-02-18 06:33:29

标签: javascript jquery pdf browser

此代码我正在尝试,但没有任何错误,它没有显示任何东西给我。

if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    save.download = fileName || 'unknown';

    var event = document.createEvent('Event');
    event.initEvent('click', true, true);
    save.dispatchEvent(event);
    (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

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

这对我不起作用

1 个答案:

答案 0 :(得分:0)

尝试使用savedocument.body元素附加到.appendChild(),然后再致电event.initEvent('click', true, true)save.dispatchEvent(event)

var fileURL = "data:text/plain,abc", fileName = "file.txt";

if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    save.download = fileName || 'unknown';
    var event = document.createEvent('Event');
    // append `a` element : `save` to `document.body` here
    document.body.appendChild(save);
    event.initEvent('click', true, true);
    save.dispatchEvent(event);
   //  (window.URL || window.webkitURL).revokeObjectURL(save.href);
}