JsPDF 不支持日语

问题描述 投票:0回答:2

我在我的 React 项目中使用 JsPDF,在为日文版保存 pdf 时遇到了一些问题,但它在英文版中运行良好。

问题 有时它会打印一些随机的特殊字符和 有时它不会在 pdf 上打印任何内容。

任何帮助将不胜感激。

这是我的代码

import React from "react";
import jsPDF from 'jspdf';
import "./styles.css";

const HelloWorldJapanese = 'こんにちは世界';

export default function App() {

  const downloadPdf = () => {
    const doc = new jsPDF()
    doc.text('Hello world!', 10, 10)
    doc.save('a4.pdf')
  }

  const downloadJapanesePDF = () => {
    const doc = new jsPDF();
    doc.text(HelloWorldJapanese, 10, 10)
    doc.save('a4.pdf');
  }

  return (
    <div className="App">
     <button onClick={downloadPdF}>Download Pdf</button>
     <br />
     <button onClick={downloadJapanesePDF}>Download Japanese Pdf</button>
    </div>
  );
}

沙盒演示:https://codesandbox.io/s/jspdf-bk7p3

javascript reactjs jspdf
2个回答
2
投票

您必须手动添加字体文件。例如,在 jsPDF git

doc.addFont("test/reference/MouhitsuBold.ttf", "Mouhitsu", "bold");

doc.setFont("Mouhitsu", "bold"); // set font

我在 glitch 中添加了代码以便于演示(在 glitch 中预览 pdf 只能在新窗口中显示)


0
投票

据我所知,我所做的是将 MouhitsuBold.ttf 转换为 base64,并将其放入文件(只要您知道如何将 base64string 称为 js 文件或 txt 文件,您就可以选择所需的文件类型但我的是这样的 js 文件)

export default {
myFunction(){
return myBase64Txt
}
}

您可以将该函数导入其他文件

import myFunction from "<thelocationofthefile>"

之后我使用

 doc.addFileToVFS("MS-Gothic_new.ttf",myFunction.myFunction());

然后

  doc.addFont("MS-Gothic_new.ttf", "MS-Gothic_new", "bold");

 doc.setFont("MS-Gothic_new", "bold");

你也可以做其他的想法,你只需要将MouhitsuBold.ttf的base64导入VFS

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.