[Python] How can I insert an image with a clickable hyperlink on the first page of a PDF using...

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to programmatically add a clickable image icon to the top-left corner of the first page of a PDF file using Python. I want the icon to link to a URL.

    what I tried using reportlab and PyPDF2:

    from PyPDF2 import PdfReader, PdfWriter
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.units import inch
    import io

    # Input paths
    pdf_path = "original.pdf"
    icon_path = "icon.jpeg"
    output_pdf_path = "output.pdf"

    # Set up canvas for overlay
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)

    # Coordinates for top-left corner with padding
    x, y = 40, 792 - 40 - inch
    can.drawImage(icon_path, x, y, width=inch, height=inch)
    can.linkURL("https://t.me/newsmalayalampdf", (x, y, x + inch, y + inch), relative=0)
    can.save()
    packet.seek(0)

    # Merge overlay with original PDF
    overlay = PdfReader(packet)
    reader = PdfReader(pdf_path)
    writer = PdfWriter()
    first_page = reader.pages[0]
    first_page.merge_page(overlay.pages[0])
    writer.add_page(first_page)
    for page in reader.pages[1:]:
    writer.add_page(page)
    with open(output_pdf_path, "wb") as f:
    writer.write(f)


    Despite setting the coordinates for the top-left, the image still appears somewhere in the middle of the page in the output. I've tried recalculating the Y position using the letter page height, but no luck.

    What is the correct way to align an image with a hyperlink in the top-left of a PDF page using ReportLab and PyPDF2?

    Continue reading...

Compartilhe esta Página