Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt PDFs in python

Is there a possible and way to encrypt PDF-Files in python? One possibility is to zip the PDFs but is there another ? Thanks for your help regards Felix

like image 823
Felix Becker Avatar asked Apr 18 '17 14:04

Felix Becker


People also ask

Can you Encrypt PDFs?

Open the PDF and choose Tools > Protection > Encrypt > Encrypt with Password 6. If you receive a prompt, click Yes to change the security. 7. Select Require A Password To Open The Document, then type the password in the corresponding field.

How do I Encrypt a PDF attachment?

Add a password to Adobe Acrobat (pdf)Open the PDF and choose Tools > Protect > Encrypt > Encrypt with Password. If you receive a prompt, click Yes to change the security. Select Require a Password to Open the Document, then type the password in the corresponding field.


Video Answer


3 Answers

You can use 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)

For more information, check out the PdfFileWriter docs.

like image 145
J08nY Avatar answered Oct 17 '22 22:10

J08nY


PikePdf which is python's adaptation of QPDF, is by far the better option. This is especially helpful if you have a file that has text in languages other than English.

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()
like image 7
Asad Rauf Avatar answered Oct 18 '22 00:10

Asad Rauf


You can use PyPDF2

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()
like image 6
Siddhesh Suthar Avatar answered Oct 17 '22 22:10

Siddhesh Suthar