archiverjs / node-archiver

a streaming interface for archive generation
https://www.archiverjs.com
MIT License
2.8k stars 220 forks source link

Zipping PDF file #332

Open josephchan91 opened 6 years ago

josephchan91 commented 6 years ago

Hi,

Thanks for the really helpful library! I have a web service that accepts some transaction data and generates two files: 1 PDF file (using PDFKit) and 1 excel file (using xlsx). I'm using node-archiver to add these 2 files to a zip file that is then downloaded by the client browser. However, when I open the zip file, the PDF file is 0kb while the excel file works fine. Here's my code:

const archive = archiver("zip", { zlib: { level: 9 } });
const output = fs.createWriteStream(myZipPath);
archive.pipe(output);

output.on("close", function() {
  callback(null, myZipPath);
});

archive.append(excelFilePath, { name: "excel-file.xlsx" });
archive.append(pdfFilePath, { name: "pdf-file.pdf" });

archive.finalize();

Has anyone worked with zipping PDF files?

Thanks so much, Joseph

michalCapo commented 6 years ago

This one worked for me

        let archive = archiver('zip', {zlib: {level: 2}});
        const file_name = os.tmpdir() + '/' + U.GUID(20);

        archive.on('finish', function () {
            archive.pipe(fs.createWriteStream(file_name));
        });

        archive.on('end', function () {
          // archive is available
        });

        for (o of orders) {
            let name = // basic name;
            let path = // a pdf file path;

            archive.append(fs.createReadStream(path), {name: `${name}.pdf`})
        }

        archive.finalize();
isorsa commented 3 years ago
        const archive = archiver('zip', {zlib: {level: 9}});
        const fileName = 'archive.zip';

        archive.attachement(fileName);
        archive.pipe(res);

        archive.on('end', function () {
          // delete files after archiving
        });

        for (const file of files) {
            archive.file(file.path, {name: `${file.name}.pdf`})
        }
        archive.finalize();