在Python中保存PDF文件可以通过多种方式实现,以下是几种常见的方法:
方法一:使用Spire.PDF
from spire.pdf import PdfDocument
创建PDF文档对象
pdf = PdfDocument()
添加页面并绘制内容
pdf.add_page()
pdf.set_font('Arial', size=15)
pdf.cell(200, 10, txt='Hello World', ln=1, align='C')
pdf.cell(200, 10, txt='This is a article.', ln=2, align='C')
保存PDF文档到文件
pdf.save_to_file('test.pdf')
方法二:使用FPDF
FPDF是一个用于创建PDF文档的库。
from fpdf import FPDF
创建PDF文档对象
pdf = FPDF()
添加页面
pdf.add_page()
设置字体大小和字体
pdf.set_font('Arial', size=15)
添加文本内容
pdf.cell(200, 10, txt='Hello World', ln=1, align='C')
pdf.cell(200, 10, txt='This is a article.', ln=2, align='C')
保存PDF文档到文件
pdf.output('test.pdf')
方法三:使用PyPDF2
PyPDF2是一个用于合并、拆分、旋转、裁剪、加密和解密PDF文件的库。
from PyPDF2 import PdfFileWriter, PdfFileReader
创建一个PdfFileWriter对象
pdf_writer = PdfFileWriter()
循环遍历每个PDF文件
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
创建一个PdfFileReader对象
pdf_reader = PdfFileReader(filename)
循环遍历每一页,第一页除外
for page_num in range(pdf_reader.numPages - 1):
将页面添加到输出PDF
pdf_writer.addPage(pdf_reader.getPage(page_num))
将输出PDF写入一个文件
with open('allminutes.pdf', 'wb') as output_file:
pdf_writer.write(output_file)
方法四:使用pdfkit
pdfkit是一个将HTML内容转换为PDF文件的库,它依赖于wkhtmltopdf工具。
import pdfkit
将HTML内容保存为PDF
pdfkit.from_url('http://example.com', 'output.pdf')
方法五:使用matplotlib保存图表为PDF
如果你想在Python中绘制图表并保存为PDF,可以使用matplotlib。
import matplotlib.pyplot as plt
绘制折线图
x1 = [1, 2, 3, 4, 5]
y1 = [5, 5.5, 7, 9, 12]
plt.plot(x1, y1, '-ro', ms=5)
保存为PDF
plt.savefig('tmp.pdf', bbox_inches='tight')
plt.show()
以上方法可以帮助你在Python中保存PDF文件。请选择适合你需求的方法进行操作