【问题标题】:Parse html with PdfMake-wrapper使用 PdfMake-wrapper 解析 html
【发布时间】:2019-11-01 09:59:50
【问题描述】:

我正在开发一个必须创建 pdf 的 Angular 网站,并且我正在使用 PdfMake-wrapper (https://github.com/Lugriz/pdfmake-wrapper)。

这是我的功能:

async pdf() {

PdfMakeWrapper.setFonts(pdfFonts);
const pdf = new PdfMakeWrapper();

pdf.pageSize('A4');
pdf.pageMargins([40, 60, 40, 60]);
pdf.pageOrientation('portrait');

pdf.header(this.bando.name);

pdf.add('Descrizione Bando');
pdf.add(this.bando.desc);

pdf.create().download();

}

问题是“this.bando.desc”是 html 文本(它包含表格、div ecc..),我想像我的 html 一样格式化我的 pdf。 我该怎么做?

【问题讨论】:

    标签: angular pdf pdfmake


    【解决方案1】:

    我建议不要直接创建 PDF,因为它需要大量不同于 HTML 的格式。最好创建一个 HTML 文档,然后将其转换为 PDF。我在最近的一个项目(打印 mtg 卡片组)中使用了它,并且效果非常好:

    import pdfkit
    from jinja2 import Template, Environment, FileSystemLoader
    
    
    class Html(object):
        def __init__(self):
            self.template: Optional[Template] = None
    
        def load_template(self):
            template_loader = FileSystemLoader(searchpath="./")
            template_env = Environment(loader=template_loader)
            self.template = template_env.get_template("template.html")
    
        def write_html(self, deck_name: str, data: list):
            with io.open("index.html", mode="w", encoding="utf-8") as fh:
                if self.template:
                    fh.write(self.template.render(deck_name=deck_name, rows=data))
    
    class Pdf(object):
        def __init__(self, deck_name: str):
            self.deck_name = deck_name
            self.options = {
                'margin-left': '5mm',
                'margin-right': '5mm',
                'margin-top': '5mm',
                'margin-bottom': '5mm',
            }
    
        def create(self):
            # create pdf
            pdfkit.from_file('index.html', f'{self.deck_name}.pdf', options=self.options)
    
    html = Html()
    html.load_template()
    html.write_html(deck_name=deck_name, data=rows)
    pdf = Pdf(deck_name=deck_name)
    pdf.create()
    

    我猜如果不做任何更改,代码将无法运行,因为我只是尝试将其剥离为基本功能,但您可以了解它是如何工作的。

    它使用Jinja2作为模板引擎以便于格式化,然后使用pdfkit模块将html导出为带有wkhtmltopdf的pdf,可以从https://wkhtmltopdf.org/下载

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2011-11-15
      • 2011-04-03
      • 2021-07-12
      相关资源
      最近更新 更多