使用JSZip压缩驻留在服务器上的PDF

时间:2014-04-04 10:26:25

标签: javascript pdf jszip

目前似乎无法做到这一点。有人做过吗?我只想要一些PDF文件添加到zip文件夹中!

1 个答案:

答案 0 :(得分:1)

很抱歉这篇帖子中缺少链接:这是我在stackoverflow上的第一篇文章,正如错误信息所示," [我]需要至少10个声望才能发布2个以上的链接。"


要下载pdf(或任何二进制文件),您可以使用xhr.responseType = "arraybuffer"获取原始内容(警告:这不会在IE 6-9中工作,更多内容如下)。您不能使用jQuery来执行此操作(但请参阅github.com/jquery/jquery/pull/1525),但原始xhr查询或任何处理二进制数据的ajax库都可以使用。例如github.com/Stuk/jszip-utils上的jszip-utils(免责声明:我是这个库的贡献者)。

我最近在JSZip文档上工作过(github.com/Stuk/jszip/pull/114),我添加了一个你想要做的事情的例子。拉取请求仍处于待处理状态,因此这里是临时网址:http://dduponchel.github.io/temp-jszip-documentation/documentation/examples/downloader.html

合并后应该在http://stuk.github.io/jszip/documentation/examples/downloader.html

以下是代码:

此函数使用JSZipUtils并将结果包装到jQuery.Deferred中,但任何可以返回ArrayBuffer或Uint8Array的库都可以工作。

/**
 * Fetch the content, add it to the JSZip object
 * and use a jQuery deferred to hold the result.
 * @param {String} url the url of the content to fetch.
 * @param {String} filename the filename to use in the JSZip object.
 * @param {JSZip} zip the JSZip instance.
 * @return {jQuery.Deferred} the deferred containing the data.
 */
function deferredAddZip(url, filename, zip) {
    var deferred = $.Deferred();
    JSZipUtils.getBinaryContent(url, function (err, data) {
        if(err) {
            deferred.reject(err);
        } else {
            zip.file(filename, data, {binary:true});
            deferred.resolve(data);
        }
    });
    return deferred;
}

这是主要功能,它使用FileSaver.js作为saveAs的polyfill:

var $form = $("#download_form").on("submit", function () {

    var zip = new JSZip();
    var deferreds = [];

    // find every checked item
    $(this).find(":checked").each(function () {
        var url = $(this).data("url");
        var filename = url.replace(/.*\//g, "");
        deferreds.push(deferredAddZip(url, filename, zip));
    });

    // when everything has been downloaded, we can trigger the dl
    $.when.apply($, deferreds).done(function () {
        var blob = zip.generate({type:"blob"});

        // see FileSaver.js
        saveAs(blob, "example.zip");
    }).fail(function (err) {
        // handle the error here
    });
    return false;
});

关于IE 6-9的注意事项:jszip和jszip-utils支持IE 6-9但没有ArrayBuffer / Uint8Array,你的性能会很差。

编辑:链接JSZip Utils GitHub:https://github.com/Stuk/jszip-utils