社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

【Python】如何用Python来操作PDF文件,建议收藏

机器学习初学者 • 5 年前 • 500 次点击  
今天这篇文章,我们不谈热点,毕竟最近谈论的热点有点多了,也有点腻了,我们来讲一些Python运用实践当中的小技巧,用Python来操作和处理PDF文件,通过本篇文章,读者朋友大概会学会

1. 通过Python脚本来创建PDF文件

2. 加密或给PDF文件上锁

3. 将多份PDF文件合并起来

4. PDF文件上水印


好,那就由小编一个一个来给大家演示看




1
通过Python脚本来创建PDF文件

我们首先来创建一个PDF文件,在下面的代码当中我们是用“reportlab”的模块,要是该模块没有被安装的话,可以通过下面的命令行来进行安装

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple reportlab

然后创建PDF文件的代码,在文件当中输入“Hello World”内容,默认的输入是从左上角开始输入,

from reportlab.pdfgen import canvasreport = canvas.Canvas("file1.pdf")report.drawString(50, 800, "This is an example for Medium")report.save()




2
加密或给PDF文件上锁

有一些PDF文件当中有重要的内容,需要将其加密、上锁,我们可以通过以下的代码来实现,用到的密码是“hello”,结果会新生成一个加密过后的PDF文件叫做“new_encrypted.pdf”,代码如下

from PyPDF2 import PdfFileReader, PdfFileWriter
encrypted_file = PdfFileWriter()original = PdfFileReader("棉花.pdf")number_of_pages = original.numPages
for i in range(number_of_pages): page = original.getPage(i) encrypted_file.addPage(page)
password = "hello"encrypted_file.encrypt(password)
with open("new_encrypted.pdf", "wb")as file: encrypted_file.write(file)




3
合并多份PDF文件

下面,我们将通过几行Python的代码来实现两个PDF文件的合并,我们用到了“PdfFileMerger()”方法,代码如下

from PyPDF2 import PdfFileReader, PdfFileMerger
first_file = PdfFileReader("棉花.pdf")second_file = PdfFileReader("30岁将就.pdf")
output = PdfFileMerger()
output.append(first_file)output.append(second_file)output.write("new_merged.pdf")




4
给PDF文件添加水印

有时候我们需要给PDF文件添加水印,原理是们手上有两个PDF文件,其中一个PDF文件是没有水印的,另外一个是有水印的,我们将这两个PDF文件合并,并且生成一个新的PDF文件

from PyPDF2 import PdfFileReader,PdfFileWriter
original_file = "file1.pdf"watermarked_pdf = "PDF_watermarked.pdf"output_file = "output.pdf"
input_file = open(original_file, 'rb')input_pdf = PdfFileReader(input_file)watermark_file = open(watermarked_pdf, 'rb')watermark_pdf = PdfFileReader(watermark_file)watermark_page = watermark_pdf.getPage(0)pdf_page = input_pdf.getPage(0)
pdf_page.mergePage(watermark_page)output = PdfFileWriter()output.addPage(pdf_page)output_file = open(output_file, 'wb')output.write(output_file)output_file.close()watermark_file.close()input_file.close()
往期精彩回顾




本站qq群851320808,加入微信群请扫码:




Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/118947