【问题标题】:How to convert html documents to pdf using vanilla JavaScript如何使用 vanilla JavaScript 将 html 文档转换为 pdf
【发布时间】:2021-08-16 15:41:41
【问题描述】:

我正在使用带有 HTML 布局的 vanilla JavaScript 创建文档表单。我想允许用户下载 PDF 格式的表单视图。

所以我想在 UI 中有一个下载按钮,一旦用户单击该按钮,我希望将表单下载为 PDF 格式。

实现这一目标的最佳方法是什么?

另外,我使用了jsPDF,但是韩文字体不能正常工作。

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"]
    }]
  })
});

结果:

【问题讨论】:

    标签: javascript html pdf jspdf


    【解决方案1】:

    问题在于底层的 html2canvas,它无法访问字体。您需要将它包含在您的 css 中,这应该允许 html2canvas 拾取它。

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

    您可以通过传递文本而不是 html(然后直接使用 jsPDF)来确认问题不在于 jsPDF:

    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();
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2022-12-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多