niklasvh / html2canvas

Screenshots with JavaScript
https://html2canvas.hertzen.com/
MIT License
30.58k stars 4.81k forks source link

Custom font ignored and default font used instead to generate image/pdf. #3062

Open sh00nyan opened 1 year ago

sh00nyan commented 1 year ago

I am using html2pdf.js, html2canvas, jspdf to generate PDF of rendered html page.

I am also using custom font for the application which is locally served.

The font configuration is:

/* Inter font configuration */
@font-face {
  font-family: 'Inter var';
  font-weight: 100 900;
  font-display: swap;
  font-style: normal;
  font-named-instance: 'Regular';
  src: url('/assets/fonts/Inter/Inter-roman.var.woff2?v=3.19') format('woff2');
}
@font-face {
  font-family: 'Inter var';
  font-weight: 100 900;
  font-display: swap;
  font-style: italic;
  font-named-instance: 'Italic';
  src: url('/assets/fonts/Inter/Inter-italic.var.woff2?v=3.19') format('woff2');
}

The code to generate PDF is:

const savePDF = () => {
  const element = document.getElementById('print-content')

  const options = {
    margin: 2,
    filename:  'download.pdf',
    pagebreak: { mode: 'css', after: '.break-point' },
    image: { type: 'jpeg', quality: 1 },
    html2canvas: {
      scale: 2,
      dpi: 300,
      width: 795,
      letterRendering: true,
      useCORS: true,
    },
    jsPDF: {
      unit: 'mm',
      format: 'a4',
      orientation: 'portrait',
    },
  }
  html2pdf()
    .from(element)
    .set(options)
    .toContainer()
    .toCanvas()
    .toImg()
    .toPdf()
    .save()
}

The application is configured to use Inter var font which is working fine. But when the PDF is generated, the PDF uses 'Helvetica' instead. I understand that it is html2canvas which is supposed to use the font. The Inter font also supports ligatures and I have enabled some features like tabular numbers, alternate numbers etc., How to get the custom font used ?

https://rsms.me/inter/#features

chenminmin199300 commented 9 months ago

I encountered the same problem, when using the custom font, the page display is normal, but I use the html2canvas screenshot, the custom font does not work