简体   繁体   English

如何使用香草 JavaScript 将 html 文档转换为 pdf

[英]How to convert html documents to pdf using vanilla JavaScript

I'm working on creating document forms using vanilla JavaScript with HTML layout.我正在使用带有 HTML 布局的香草 JavaScript 创建文档 forms。 I want to allow users to download the form view in PDF format.我想让用户下载 PDF 格式的表单视图。

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.所以我想在 UI 中有一个下载按钮,一旦用户单击该按钮,我希望将表单下载为 PDF 格式。

What's the best way to achieve that?实现这一目标的最佳方法是什么?

Additionally, I've used jsPDF but korean font is not working properly.此外,我使用jsPDF ,但韩文字体无法正常工作。

index.html 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应用程序.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:结果:

在此处输入图像描述

The problem is with the underlying html2canvas, which doesn't have access to the font.问题在于底层的 html2canvas,它无权访问字体。 You need to include it in your css, which should allow html2canvas to pick it up.您需要将它包含在您的 css 中,这应该允许 html2canvas 接收它。

@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):您可以通过传递文本而不是 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM