How to download zip file after creating PDF with pdfMake

1.9k Views Asked by At

I am using pdfMake to create pdf document in my angular project. Meanwhile, I want to create the zip file containing my multiple pdf documents.

Are there any possible to do so? Your answers or ideas are appreciated.

1

There are 1 best solutions below

1
On

Did a similar task this way. Wrote a website in react.

import JSZip from 'jszip';
import * as FileSaver from "file-saver";
import * as pdfMake from "pdfmake/build/pdfmake";
interface forzip {
  array: any[];
  wordHeaders: string[];
  dataKeys: string[];
  image?: any;
  headerName?:string
}
export const getHtmlStringFromJson = (
  data: {}[],
  headers: string[],
  dataKeys: string[],
  headerName?:string
) => {
  let tableHeaders = "";
  headers.forEach((h) => (tableHeaders += "<th>" + h + "</th>"));
  let tableBody = "";
  data?.forEach((d) => {
    tableBody += "<tr>";
    dataKeys.forEach((dk) => {
      //@ts-ignore
      tableBody += "<td>" + d[dk] + "</td>";
    });
    tableBody += "</tr>";
  });
  let html =
    `<p>`+headerName!+`</p>
    <table border="1">
      <thead>
        <tr>` +
    tableHeaders +
    `</tr>
      </thead>
      <tbody>` +
    tableBody +
    `</tbody>
    </table>`;
  return html;
};
export const export2zip = (arrforzip:forzip[]) => {
  (window as any).pdfMake.vfs = pdfFonts.pdfMake.vfs;

  const zip = new JSZip();
  var  pdf = zip.folder("pdf");

  arrforzip.map(function(forpdf,i) {
    let htmlString = getHtmlStringFromJson(forpdf.array, forpdf.wordHeaders, 
    forpdf.dataKeys,forpdf.headerName!);
    let htmlPdf = htmlToPdfmake(htmlString)
    let pdfData = pdfMake.createPdf({content:htmlPdf});
    pdfData.getBlob(blob => {
    pdf?.file(
      `${forpdf.headerName}.pdf`,
      blob,
      { binary: true }
    );
    });
  })
  zip.generateAsync({type:"blob"}).then(function (blob) {
  zip.generateAsync({type:"blob"})
  .then(function(content) {FileSaver.saveAs(content, `examples.zip`);});
  });
};

export2zip(completData)