Add image over pdf

Add image into a pdf pages

from io import BytesIO

from PyPDF2 import PdfWriter, PdfReader
from reportlab.pdfgen import canvas


def get_bottom_right_coordinates(pdf_path):
    with open(pdf_path, 'rb') as pdf_file:
        pdf_reader = PdfReader(pdf_file)

        # Assuming the PDF has only one page (change accordingly for multiple pages)
        page = pdf_reader.pages[0]

        # Get page size
        page_width = int(page.mediabox.width)
        print(f"page_width: {page_width}")
        page_height = page.mediabox.height

        # Bottom right coordinates
        bottom_right_x = page_width
        bottom_right_y = 0  # Assumes (0,0) is the bottom left corner

        return bottom_right_x, bottom_right_y


# Example usage
def method_5():
    # Using ReportLab to insert image into PDF
    imgTemp = BytesIO()
    imgDoc = canvas.Canvas(imgTemp)

    # Draw image on Canvas and save PDF in buffer
    imgPath = "sample-image.png"

    x, y = get_bottom_right_coordinates(pdf_path="input.pdf")
    print(f"Coordinates: x: {x}, y: {y}")

    x = 400
    y = 15
    print(f"Coordinates: x: {x}, y: {y}")
    imgDoc.drawImage(imgPath, x, y, 200, 90)  # at (399,760) with size 160x160
    imgDoc.save()

    # Use PyPDF to merge the image-PDF into the template
    pdf_template_path = "input.pdf"
    pdf_output_path = "output.pdf"

    # Read the existing PDF template
    existing_pdf = PdfReader(open(pdf_template_path, "rb"))

    # Create a PDF writer to save the result
    output = PdfWriter()

    # Merge the pages
    for page_num in range(len(existing_pdf.pages)):
        page = existing_pdf.pages[page_num]

        # Merge the image page with the template page
        img_pdf = PdfReader(BytesIO(imgTemp.getvalue()))
        img_page = img_pdf.pages[0]
        page.merge_page(img_page)

        # Add the modified page to the new PDF
        output.add_page(page)

    # Save the result
    with open(pdf_output_path, "wb") as output_file:
        output.write(output_file)


if __name__ == '__main__':
    method_5()

Last updated