python html转pdf

 

import pdfkit  # 需要pip安装
import os


class HtmlToPdf(object):

    def __init__(self, file, *, html='', margin=('0.75in', '0.75in', '0.5in', '0.75in')):
        self.html = html
        self.file = file
        self.options = {
                'margin-top': margin[0],
                'margin-right': margin[1],
                'margin-bottom': margin[2],
                'margin-left': margin[3],
        }

    def set_html(self, html):
        self.html = html

    def create(self):  # 新建文件
        try:
            folder = os.path.dirname(self.file)
            if not os.path.exists(folder):
                os.makedirs(folder)
            pdfkit.from_string(self.html, self.file, options=self.options)
        except Exception as e:
            return False
        return True


if __name__ == '__main__':
    html_to_pdf = HtmlToPdf(r'/home/www/test.pdf')
    html_to_pdf.set_html('<html><body><b>test</b></body></html>')
    html_to_pdf.create()

 

posted @ 2020-12-03 10:20  小小小光子  阅读(200)  评论(0编辑  收藏  举报