使用Python和xhtml2pdf创建PDF
嗨,大家好!。在本文中,我想与您分享一些指南,该指南将向您展示如何使用Python和xhtml2pdf创建pdf文件。
该xhtml2pdf LIB被用来从HTML文件创建PDF文件。这只是我为自己制作的指南,但我想与您分享。
警告:另外,这是我出于实验目的而编写的指南,我没有在生产环境中使用它。因此,必须牢记在生产中使用它可能会有问题。创建PDF文件的更好的替代方法是http://weasyprint.org/。
要求
- Python(我使用Python 3.8.2)
- 点(我使用点20.1.1)
设置项目
为了创建我们的项目,我们将使用virtualenv,为该项目创建一个隔离的python环境。但是,您也可以使用pyenv或venv。
因此,首先,我们必须安装venv
。
pip3 install virtualenv
现在,我们必须创建项目文件夹并设置virtualenv。
# Creating a project folder
mkdir pdfs-example
cd pdfs-example
# Creating the virtual environment
virtualenv env
# Activate the virtual environment
source env/bin/activate
# Create our main file
touch main.py
注意:要退出环境,您只需编写deactivate
。
安装依赖项
要创建我们的PDF文件,我们需要安装该xhtml2pdf
库。该库也取决于html5lib
和 reportlab
。
pip install reportlab # https://pypi.org/project/reportlab/
pip install html5lib # https://pypi.org/project/html5lib/
pip install xhtml2pdf
注意:我们需要一个比0.1a1
使用Python3 高的xhtml2pdf版本。
我们可以使用以下命令查看已安装的依赖项。
# Installed dependencies
pip freeze
# The above mentioned command will list something like the following
html5lib==1.1
Pillow==7.2.0
PyPDF2==1.26.0
reportlab==3.5.50
six==1.15.0
webencodings==0.5.1
xhtml2pdf==0.2.4
我们还可以导出依赖项。
pip freeze > requirements.txt
并从requirements.txt
文件安装我们的依赖项。
pip install -r requirements.txt
从字符串生成PDF
现在我们已经安装了必要的模块,我们可以开始编写代码了。首先,我们必须导入xhtml2pdf模块,这将帮助我们创建PDF文件。
# main.py
# import section ....
from xhtml2pdf import pisa # import python module
# ....
现在,我们可以定义一些常量。
# main.py
# Constants section ....
# Content to write in our PDF file.
SOURCE = "<html><body><p>PDF from string</p></body></html>"
# Filename for our PDF file.
OUTPUT_FILENAME = "test.pdf"
# ....
好的,我们将创建一个基本函数以在其他函数中重用,并避免代码重复。
# main.py
# Methods section ....
def html_to_pdf(content, output):
"""
Generate a pdf using a string content
Parameters
----------
content : str
content to write in the pdf file
output : str
name of the file to create
"""
# Open file to write
result_file = open(output, "w+b") # w+b to write in binary mode.
# convert HTML to PDF
pisa_status = pisa.CreatePDF(
content, # the HTML to convert
dest=result_file # file handle to recieve result
)
# close output file
result_file.close()
result = pisa_status.err
if not result:
print("Successfully created PDF")
else:
print("Error: unable to create the PDF")
# return False on success and True on errors
return result
# ....
一旦有了基本功能,就可以创建我们的from_text
功能。
# main.py
# Methods section ....
def from_text(source, output):
"""
Generate a pdf from a plain string
Parameters
----------
source : str
content to write in the pdf file
output : str
name of the file to create
"""
html_to_pdf(source, output)
# ....
我们的main
职能如下。
# main.py
# import section ....
import sys
# Main section ...
if __name__ == "__main__":
if len(sys.argv)> 1 :
if sys.argv[1] == '--help':
print('Info: ')
print('--help List the options to send an email')
print('--text Create a PDF file from a string')
print('--template Create a PDF file from a template')
elif sys.argv[1] == '--text':
print("Creating a PDF file from a string")
from_text(SOURCE, OUTPUT_FILENAME)
else:
print("Please give the type of message to send.")
print("For help execute `python main.py --help`")
我们可以通过在终端中执行以下命令来测试功能。
python main.py --text
# Creating a PDF file from a string
# Successfully created PDF
从模板生成PDF
在这里,我们将使用HTML模板生成PDF文件。我们必须记住,xhtml2pdf直到HTML4 才支持。因此,首先,我们必须创建一个HTML文件,该文件将充当我们PDF文件的模板。
touch template.html
我们将定义一个简单的html模板。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PDF Generator</title>
</head>
<body>
<h1 style="color:red;">First PDF</h1>
<h2 style="color:blue;">PDF with html template</h2>
<p>John</p>
<p>Snow</p>
<p>35</p>
</body>
</html>
创建一个新的常量来定义我们的模板文件。
# main.py
# Constants section ....
# Template file name
TEMPLATE_FILE = "template.html"
# ....
现在,我们可以创建函数来读取模板并创建PDF文件。
# main.py
# Methods section ....
def from_template(template, output):
"""
Generate a pdf from a html file
Parameters
----------
source : str
content to write in the pdf file
output : str
name of the file to create
"""
# Reading our template
source_html = open(template, "r")
content = source_html.read() # the HTML to convert
source_html.close() # close template file
html_to_pdf(content, output)
# ....
将选项添加到我们的主要功能。
# main.py
# Main section ...
if __name__ == "__main__":
# ....
if len(sys.argv)> 1 :
# if ....
elif sys.argv[1] == '--template':
print("Creating a PDF file from a template")
from_template(TEMPLATE_FILE, OUTPUT_FILENAME)
else:
# ....
我们可以通过在终端中执行以下命令来测试功能。
python main.py --template
# Creating a PDF file from a template
# Successfully created PDF
最后的话
感谢您阅读本文,您可以在这里找到本指南的代码。
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 使用Python和xhtml2pdf创建PDF
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。