pdfmake for front-end export PDF

pdfmake generates pdf by editing the pdf description object in a specific format and passing it to pafmake

The default pdfmake does not support Chinese

How to support Chinese

To support Chinese, you need to configure Chinese fonts. According to the documentation, there are two ways: 1. Use online font configuration. 2. Use local vfs (virtual file system) to configure fonts. This article introduces the second.

The steps described in the documentation:

  • Install pdfmake npm install pdfmake

    Install pdfmake

  • Go to package directory ./node_modules/pdfmake/

    enter ./node_modules/pdfmake/directory

  • Create the examples/fonts subdirectory in your pdfmake code directory, if it doesn’t already exist.

    examples/fontsCreate a subdirectory under the pdfmake directory

  • Copy your fonts (and other files you wish to embed) into the examples/fonts subdirectory.

    Put the character .ttf file you want to use into examples/fontsthe directory, the Chinese font files are relatively large, you can enter the font folder of the computer, find a smaller one and put it in or download the font you want

  • Run command node build-vfs.js "./examples/fonts". Or run node build-vfs.js to show help.

    Execute in the pdfmake directorynode build-vfs.js "./examples/fonts"

  • Include your new build/vfs_fonts.js file in your code (in the same way you include pdfmake.js or pdfmake.min.js).

    Then a file buildwill be generated under the folder vfs_fonts.js, this file is the font file we want to use, you can open this file, you can see the font name and other information

Above we have generated Chinese fonts

how to use

// 在项目里引入pdfmake
import pdfMake from "pdfmake/build/pdfmake";

// 我把上面生成的字体放入了 vue 中的static文件夹,我使用的是FZYTK.TTF
// 这样直接引入就可以,不需要额外引入原字体文件(FZYTK.TTF)
const vfs_fonts = require('../xxx/static/vfs_fonts');
pdfMake.vfs = vfs_fonts;

// 定义字体 
pdfMake.fonts = {
    
    
    // webfont是字体名,可以自定义,下面需要用这个名字配置字体
    webfont: {
    
    
        // FZYTK.TTF 这个文件已经在 我们生成的 vfs_font.js 文件中,且已经引入,所以可以直接使用
        normal: "FZYTK.TTF",
        bold: "FZYTK.TTF",
        italics: "FZYTK.TTF",
        bolditalics: "FZYTK.TTF",
    },
    // 可以定义多个字体
    anotherFontName: {
    
    
     (...)
    },
};

// 下面我们来定义 pdfmake需要用的 pdf文件描述对象
// 这个描述对象 具体的字段可以参考官方文档
var docDefinition = {
    
    
    content: "这是一段中文。welcome to China",
    defaultStyle: {
    
    
        // 设置我们定义的字体为默认字体
        font: "webfont",
    },
};

pdfMake.createPdf(docDefinition).download("文件名", () => {
    
    
    console.log("complete");
});

Guess you like

Origin blog.csdn.net/mochenangel/article/details/118634758