python--html to pdf

本文介绍如何在Debian/Ubuntu服务器上安装wkhtmltopdf,并通过pdfkit库将HTML文件、字符串及网页转换为PDF文件。提供详细的安装步骤及Python代码示例。
Debian/Ubuntu

To install wkhtmltopdf in a Debian/Ubuntu server, follow this steps(as root):

apt-get install wkhtmltopdf
apt-get install xvfb
echo -e '#!/bin/bash\nxvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf -q $*' > /usr/bin/wkhtmltopdf.sh
chmod a+x /usr/bin/wkhtmltopdf.sh
ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf
wkhtmltopdf http://www.google.com output.pdf

then :

pip install pdfkit


vim test.py

#coding:utf-8
#__author__:Bing
import pdfkit  
      
    pdfkit.from_file('test.html', 'out.pdf')  
     
    # Generating PDFs from strings and web-pages is equally easy:  
      
    pdfkit.from_string('Hello!', 'out.pdf')  
    pdfkit.from_url('http://google.com', 'out.pdf')  

 

转载于:https://my.oschina.net/u/2393235/blog/693567

Python中,将HTML文件转换为PDF格式可以使用多个库来实现。其中,`wkhtmltopdf` 是一个非常流行的选择,因为它基于 WebKit 渲染引擎,能够准确地将HTML内容渲染为PDF格式[^2]。此外,还可以使用 `weasyprint` 或 `pdfkit` 等库进行HTMLPDF的转换。 ### 使用 `pdfkit` 库转换 HTMLPDF `pdfkit` 是一个封装了 `wkhtmltopdf` 的Python库,使用起来非常方便。首先,需要安装 `wkhtmltopdf` 和 `pdfkit`: ```bash pip install pdfkit ``` 同时,确保你已经从 [wkhtmltopdf官网](https://wkhtmltopdf.org/downloads.html) 下载并安装了 `wkhtmltopdf` 的可执行文件。 以下是一个基本的代码示例,展示如何将HTML文件转换为PDF: ```python import pdfkit # 指定HTML文件路径和输出的PDF文件路径 input_html = 'example.html' output_pdf = 'output.pdf' # 将HTML文件转换为PDF pdfkit.from_file(input_html, output_pdf) ``` ### 使用 `weasyprint` 库转换 HTMLPDF `weasyprint` 是另一个强大的库,它可以直接将HTML和CSS渲染为PDF。安装方式如下: ```bash pip install weasyprint ``` 以下是一个使用 `weasyprint` 的示例代码: ```python from weasyprint import HTML # 指定HTML文件路径和输出的PDF文件路径 input_html = 'example.html' output_pdf = 'output.pdf' # 将HTML文件转换为PDF HTML(filename=input_html).write_pdf(output_pdf) ``` ### 自定义选项 在转换过程中,可以添加一些自定义选项,例如设置页面大小、边距等。以下是一个在 `pdfkit` 中设置选项的示例: ```python options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', } pdfkit.from_file(input_html, output_pdf, options=options) ``` ### 总结 通过 `pdfkit` 或 `weasyprint`,可以轻松地将HTML文件转换为PDF格式,并且可以根据需要进行自定义设置。这些工具非常适合用于自动化文档生成、报告导出等场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值