是否有可能和方法在python中加密PDF文件? 一种可能性是拉链PDF但是还有另一种吗? 谢谢你的帮助 问候 菲利克斯
答案 0 :(得分:5)
您可以使用PyPDF2:
from pyPDF2 import PdfFileReader, PdfFileWriter
with open("input.pdf", "rb") as in_file:
input_pdf = PdfFileReader(in_file)
output_pdf = PdfFileWriter()
output_pdf.appendPagesFromReader(input_pdf)
output_pdf.encrypt("password")
with open("output.pdf", "wb") as out_file:
output_pdf.write(out_file)
有关详情,请查看PdfFileWriter
docs。
答案 1 :(得分:2)
您可以使用[PyPDF2] [1]
import PyPDF2
pdfFile = open('input.pdf', 'rb')
# Create reader and writer object
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
# Add all pages to writer (accepted answer results into blank pages)
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
# Encrypt with your password
pdfWriter.encrypt('password')
# Write it to an output file. (you can delete unencrypted version now)
resultPdf = open('encrypted_output.pdf', 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
[1]: https://pythonhosted.org/PyPDF2/
答案 2 :(得分:0)
我强烈推荐pyAesCrypt模块。 它基于部分用C编写的加密模块。 该模块非常快,尤其是在高规格计算机中。 您可以期望在高端计算机上对3 Gb文件进行12秒的加密,因此虽然不是最好的,但它确实非常快。
一种用于加密和解密的衬里是:
import pyAesCrypt
加密:
pyAesCrypt.encryptFile(inputfile, outputfile, password, bufferSize)
解密:
pyAesCrypt.decryptFile(inputfile, outputfile, password, bufferSize)
由于这不是完整的说明,因此建议您完整阅读文档,因为它并不长。 您可以在这里找到它:https://pypi.org/project/pyAesCrypt/
答案 3 :(得分:0)
PikePdf是python对QPDF的改编,到目前为止是更好的选择。如果您的文件中包含英语以外的其他语言的文本,这将特别有用。
from pikepdf import Pdf
pdf = Pdf.open(path/to/file)
pdf.save('output_filename.pdf', encryption=pikepdf.Encryption(owner=password, user=password, R=4))
# you can change the R from 4 to 6 for 256 aes encryption
pdf.close()
答案 4 :(得分:0)
另一个选项是Aspose.PDF Cloud SDK for Python,它是一个REST API 解决方案。您可以使用从 Amazon S3、DropBox、Google Drive Storage、Google Cloud Storage、Windows Azure Storage、FTP Storage 和 Aspose Cloud Storage 中选择的云存储。
加密算法采用以下可能的值
import os
import base64
import asposepdfcloud
from asposepdfcloud.apis.pdf_api import PdfApi
from shutil import copyfile
# Get Client key and Client ID from https://cloud.aspose.com
pdf_api_client = asposepdfcloud.api_client.ApiClient(
app_key='xxxxxxxxxxxxxxxxxxxxxxxxxx',
app_sid='xxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxx')
pdf_api = PdfApi(pdf_api_client)
temp_folder="Temp"
#upload PDF file to storage
data_file = "C:/Temp/02_pages.pdf"
remote_name= "02_pages.pdf"
pdf_api.upload_file(remote_name,data_file)
out_path = "EncryptedPDF.pdf"
user_password_encoded = base64.b64encode(b'user $^Password!&')
owner_password_encoded = base64.b64encode(b'owner\//? $12^Password!&')
#Encrypte PDF document
response = pdf_api.put_encrypt_document(temp_folder + '/' + out_path, user_password_encoded, owner_password_encoded, asposepdfcloud.models.CryptoAlgorithm.AESX128, file = remote_name)
#download PDF file from storage
response_download = pdf_api.download_file(temp_folder + '/' + out_path)
copyfile(response_download, 'C:/Temp/' + out_path)
print(response)