PDF export images asynchronously and double files exported

PDF export images asynchronously and double files exported

StickmanStickman Posts: 3Questions: 2Answers: 0

I have code that works basically fine. After clicking the button responsible for exporting to PDF, a file with images is generated and downloaded, everything is great. The problem is (probably) that it happens asynchronously and two files are actually downloaded. One 'file-correct' with graphics and one 'file-invalid', without graphics. How can I change this so that only the correct file is downloaded? I removed some of the code for clarity.

I tried to add the code to live.datatables.net (https://live.datatables.net/migaloja/1/edit) but a lot of errors appear and the actual file-correct is not downloaded at all. It's strange, because these errors don't appear in the browser at all (in console) when I have the code on my site and the file-correct is exported (unfortunately with the file-invalid one).

I will mention that my programming knowledge is not so good. My code, I feel like it's sometimes a zombie product, which I put together and glue together from various code examples from the forum (gosh, it's so helpful!).

const dataTable = $('#myTable').DataTable({
    buttons: [{
        extend: 'excel',
    }, {
        extend: 'pdf',
        title: 'file-invalid',
        exportOptions: {
          format: {
            body: function (data, row, column, node) {
              if ($(node).find('input').length > 0) {
                return $(node).find('input').val();
              }
              return data;
            }
          }
        },
        async customize(doc) {
          if (doc) {
            const fetches = [];
            let imagesFetched = 0;

            for (let i = 1; i < doc.content[1].table.body.length; i++) {
              if (doc.content[1].table.body[i].length >= 4) {
                const imageSrcElement = doc.content[1].table.body[i][3].text;
                const parser = new DOMParser();
                const docHTML = parser.parseFromString(imageSrcElement, 'text/html');
                const imageSrc = docHTML.body.querySelector('img').getAttribute('src');

                try {
                  const data = await fetchImage(imageSrc);
                  doc.content[1].table.body[i][5] = {
                    alignment: 'center',
                    image: data,
                    width: 60,
                  };
                  imagesFetched++;
                } catch (error) {
                  console.error('Error fetching image at index ${i}:', error);
                }
              }
            }

            await Promise.all(fetches);
            if (imagesFetched === doc.content[1].table.body.length - 1) {
              pdfMake.createPdf(doc).download('file-correct.pdf');
            } else {
              console.error('Not all images were fetched successfully.');
            }
          }
        }
    }],
});

function fetchImage(url) {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then(response => response.blob())
      .then(blob => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      })
      .catch(reject);
  });
}

document.getElementById("export-pdf").addEventListener("click", function() {
    dataTable.button(1).trigger();
});
Sign In or Register to comment.