使用 Angular 将 HTML 文档转换为 PDF

时间:2021-06-28 21:08:03

标签: javascript html angular pdf pdfmake

我有一个 Angular 11 应用程序,我想从给定的 HTML 下载 PDF。此 HTML 不是来自我的 Angular 应用程序的组件,而是独立于应用程序的 HTML 文档,如下所示:

<!DOCTYPE html>
<html lang='en' xmlns='ttp://www.w3.org/1999/xhtml'>
    <head>
        <style> p { color: red; } </style>
    </head>
    <body>
        <p>hi there</p>
    </body>
</html>



我希望能够加载此 HTML 并按原样另存为 PDF。我尝试使用 pdfmake 创建 PDF,但它忽略了 head 标签上的样式。

import pdfMake from 'pdfmake/build/pdfmake'
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import htmlToPdfmake from 'html-to-pdfmake';

export class MyComponent {
    myHtml: string = "<!DOCTYPE html><html lang='en' 
xmlns='ttp://www.w3.org/1999/xhtml'><head><style> p { color: red; } 
</style></head><body><p>hi there</p></body></html>";

    constructor() {
        let html = htmlToPdfmake(this.myHtml);
        let documentDefinition = { content: html };
        pdfMake.createPdf(documentDefinition).open();
    }

}

PDF 生成:enter image description here

文字应该是红色的,为什么不是红色?

1 个答案:

答案 0 :(得分:0)

你可以添加这样的内联样式

<!DOCTYPE html>
<html lang='en' xmlns='ttp://www.w3.org/1999/xhtml'>
    <head>
    </head>
    <body>
        <p style="color: red;">hi there</p>
    </body>
</html>
相关问题