#TIL 35 - Fix blank image with html2pdf | ProductsWay

#TIL 35 - Fix blank image with html2pdf

Dec 31, 2022 · Dung Huynh

What

Fix blank images in PDFs generated by html2pdf.js when the source HTML includes cross-origin images.

Why

Browsers restrict canvas access when an image comes from another origin without CORS approval. Setting useCORS: true tells html2canvas to request the image anonymously with CORS, but the image server must still return an appropriate Access-Control-Allow-Origin header. This option neither bypasses CORS nor sends credentials.

How

Enable CORS in html2canvas options:

const element = document.getElementById("thread");

window
  .html2pdf()
  .set({
    filename: `${id}-${Date.now()}.pdf`,
    html2canvas: {
      scale: 2,
      useCORS: true, // The image server must allow this page's origin.
    },
  })
  .from(element)
  .save();