Challenge: Program to Add Watermark to PDF

Python Program to Add Watermark to PDFs

Python Problems for Practice

 

In this Python problem for practice you will have to write a script to automate the watermarks of your PDFs. Your task is to create a Python 3 program using the PyPDF2 library that imports a PDF file, adds a watermark to all pages, and exports the modified PDF to the desktop.

Your program should follow these specific instructions:
1. Import the PyPDF2 library.
2. Prompt the user to enter the file path of the PDF they want to modify.
3. Prompt the user to enter the text they want to use as the watermark.
4. Open the PDF file using the PyPDF2 library.
5. Iterate through each page of the PDF and add the watermark text to it.
6. Save the modified PDF file to the desktop.
7. Display a message to the user indicating the successful completion of the program.

Guidelines

  1. Import the PyPDF2 library.
  2. Ask the user to enter the file path of the PDF they want to modify and the text for the watermark.
  3. Open the PDF file using the PyPDF2 library.
  4. Iterate through each page of the PDF and add the watermark text to it.
  5. Save the modified PDF file to the desktop.
  6. Display a message to the user indicating the successful completion of the program.

Find more real Python problems here.

Source code


import PyPDF2
import os

# Prompt the user to enter the file path of the PDF and the watermark text
file_path = input("Enter the file path of the PDF: ")
watermark_text = input("Enter the text for the watermark: ")

# Open the PDF file
with open(file_path, 'rb') as file:
    reader = PyPDF2.PdfReader(file)
    writer = PyPDF2.PdfWriter()

    # Iterate through each page of the PDF and add the watermark text to it
    for page_number in range(reader.numPages):
        page = reader.getPage(page_number)
        page.mergePage(PyPDF2.pdf.PageObject.create_watermark(page, watermark_text))
        writer.addPage(page)

    # Save the modified PDF file to the desktop
    desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
    output_file_path = os.path.join(desktop_path, 'modified_pdf.pdf')
    with open(output_file_path, 'wb') as output_file:
        writer.write(output_file)

# Display a message indicating the successful completion of the program
print("The modified PDF has been saved to the desktop.")

 

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart