1

I have a function that needs to export the html page to a pdf, and I am trying to achieve that using pdfmake and html2canvas. The problem I encountered is when the image is too big to fit one page, it shifts to another leaving a lot of empty space. So I am using a function to split the image in multiple ones in case the initial one is too big.

The issue at hand is that when I am splitting an image, and only then, for example in two separate ones, both the new ones are very blurry and nothing is understandable from them, even if they are positioned correctly in the created pdf. And this issue happens only when I am splitting the image, not when everything fits on one single page (so no drawImage called).

Here is the function I am using for splitting:

function splitImage(img, content, callback, selectedFilter, currentTime, currentReference, fileName) {
      return function() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = false;
        const printHeight = (img.height * currentReference.PAGE_WIDTH) / img.width;

        canvas.width = currentReference.PAGE_WIDTH;

        for (let pages = 0; printHeight > pages * currentReference.PAGE_HEIGHT; pages++) {
          /* Don't use full height for the last image */
          canvas.height = Math.min(currentReference.PAGE_HEIGHT, printHeight - pages * currentReference.PAGE_HEIGHT);
          ctx.drawImage(
            img,
            0,
            Math.round(-pages * currentReference.PAGE_HEIGHT),
            Math.round(currentReference.PAGE_WIDTH),
            Math.round(printHeight)
          );
          content.push({
            image: canvas.toDataURL(),
            margin: [0, 5],
            width: currentReference.PAGE_WIDTH
          });
        }
        currentReference.downloadPdf(selectedFilter, currentTime, currentReference, fileName, content);
        callback();
      };
    }

The initial width and height for the img that I am using are the following ones

img.height
2691
img.width
1532

and the PAGE_WIDTH and the PAGE_HEIGHT parameters have the following values

public PAGE_HEIGHT = 705;
public PAGE_WIDTH = 550;

I tried using scale:2 when I initially use the html2canvas function, I tried using imageSmoothingEnabled = false as you can see in the code and I tried using the answer in here (which made everything even more blurry)

How can I avoid the quality loss of the new images?

Artyomska
  • 1,309
  • 5
  • 26
  • 53
  • `ctx.imageSmoothingEnabled = false;` should be set after setting the canvas width and height as those reset the context. – Mike Dec 04 '22 at 16:01

0 Answers0