Search code examples
javascripthtmlpdfjspdf

How to convert html documents to pdf using vanilla JavaScript


I’m working on creating document forms using vanilla JavaScript with HTML layout. I want to allow users to download the form view in PDF format.

So I’m thinking to have a download button in the UI and once user clicks the button, I want the form to be downloaded as PDF format.

What’s the best way to achieve that?

Additionally, I've used jsPDF but korean font is not working properly.

index.html

  <!DOCTYPE html>
  <html lang="ko">
    <head>
      <meta charset="utf-8" />
      <title>Vanilla JS</title>
    </head>
    <body>
      <div id="temp">
        <h1>안녕하세요</h1>
        <ul>
          <li>사과</li>
          <li>오렌지</li>
          <li>바나나</li>
        </ul>
      </div>
      <button id="hi">다운로드</button>
    </body>
  </html>

app.js

import {jsPDF} from 'jspdf';
import { font } from './font';

const button = document.querySelector('#hi');
const koreanTextDiv = document.querySelector('#temp');

button.addEventListener('click', () => {
  const doc = new jsPDF();

  doc.html(koreanTextDiv, {
    callback (doc) {
      // setting language
      doc.addFileToVFS('NanumGothic-Regular-normal.ttf', font);
      doc.addFont('NanumGothic-Regular-normal.ttf', 'NanumGothic-Regular', 'normal');
      doc.setFont('NanumGothic-Regular');
      doc.setLanguage('ko-KR');
      doc.save();
    },
    fontFaces: [{
      family: 'NanumGothic-Regular',
      src: ["/NanumGothic-Regular.ttf"]
    }]
  })
});

Result:

enter image description here


Solution

  • The problem is with the underlying html2canvas, which doesn't have access to the font. You need to include it in your css, which should allow html2canvas to pick it up.

    @font-face {
        font-family: 'NanumGothic-Regular';
        src: url('/fonts/NanumGothic-Regular') format('ttf');
    }
    
    body {
        font-family: 'NanumGothic-Regular';
    }
    

    You can confirm that the issue is not with jsPDF by passing text rather than html (which will then use jsPDF directly):

    doc.addFileToVFS('NanumGothic-Regular.ttf', font);
    doc.addFont('NanumGothic-Regular.ttf', 'NanumGothic-Regular', 'normal');
    doc.setFont('NanumGothic-Regular');
    doc.setLanguage('ko-KR');
    doc.text("안녕하세요", 10, 10);
    doc.save();