Create PDF with Latex equations using Angular

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

我有一个管理面板应用程序来创建数学测试,它应该有创建 pdf 文件的按钮。我使用了 pdfMake 来转换 html 但这个 html 不是用 DOM 编写的(所有测试问题都带有图像等)。这个生成的 pdf 非常大,有 20-30 页。

问题是有用MathJax写的数学方程式,它们在管理面板中很好地显示(MathJax将方程式转换为svg)。我不能从 dom 中获取这个 svg 标签,因为我在每个站点页面上只看到一个问题。我想在组件的 .ts 文件中创建相同的 svg 标签,以将其添加到我的变量中,该变量最后由 pdfMake 转换。我该怎么做?

angular latex pdf-generation mathjax pdfmake
1个回答
0
投票

以下是您可以遵循的步骤:

  1. 使用 npm 安装
    pdfmake
    MathJax
    库。
npm install pdfmake mathjax
  1. 在您的组件中导入
    pdfmake
    库并定义一个函数来生成PDF文档。
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
import * as MathJax from 'mathjax';

pdfMake.vfs = pdfFonts.pdfMake.vfs;

function generatePDF() {
    const docDefinition = {
        content: [
            {
                text: 'My Math Test',
                style: 'header'
            },
            {
                text: 'Question 1',
                style: 'subheader'
            },
            {
                text: 'Solve the following equation:',
                style: 'question'
            },
            {
                text: 'x^2 + 2x + 1 = 0',
                style: 'equation'
            }
        ],
        styles: {
            header: {
                fontSize: 22,
                bold: true
            },
            subheader: {
                fontSize: 18,
                bold: true,
                margin: [0, 15, 0, 5]
            },
            question: {
                fontSize: 14,
                margin: [0, 15, 0, 5]
            },
            equation: {
                margin: [0, 5, 0, 15],
                decoration: 'underline',
                decorationStyle: 'dashed'
            }
        }
    };

    // Generate MathJax SVG tags for the equation
    const math = new MathJax.MathJax({
        loader: {load: ['input/tex', 'output/svg']},
        tex: {packages: {'[+]': ['color']}},
        svg: {fontCache: 'global'}
    });

    math.startup().then(() => {
        const svg = math.svg('x^2 + 2x + 1 = 0');
        console.log(svg);
        // Add the SVG tag to the PDF document
        docDefinition.content[3].text = {svg: svg.outerHTML};
        pdfMake.createPdf(docDefinition).download('math-test.pdf');
    });
}

在这个例子中,我们定义了一个

docDefinition
对象,它包含我们PDF文档的内容。我们还为文档的不同元素定义样式。

然后我们使用

MathJax
库为方程
x^2 + 2x + 1 = 0
生成一个 SVG 标签。我们通过将相关元素的
text
属性设置为具有包含 SVG 标签的
svg
属性的对象来将此 SVG 标签添加到 PDF 文档中。

最后,我们使用

pdfMake.createPdf()
函数创建PDF文档,并使用
download()
方法将它下载到用户的设备上。

  1. 在组件模板中添加一个按钮,单击时调用
    generatePDF()
    函数。
<button (click)="generatePDF()">Download PDF</button>

当用户点击这个按钮时,会调用

generatePDF()
函数,生成并下载PDF文档。

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