|
| 1 | +""" |
| 2 | +Simple PDF Editor using PyPDF2 and reportlab |
| 3 | +Issue #37 for king04aman/All-In-One-Python-Projects |
| 4 | +""" |
| 5 | +import PyPDF2 |
| 6 | +from reportlab.pdfgen import canvas |
| 7 | +from reportlab.lib.pagesizes import letter |
| 8 | +import io |
| 9 | + |
| 10 | +# Insert text into a PDF (creates a new PDF with text overlay) |
| 11 | +def insert_text(input_pdf, output_pdf, text, x=100, y=700): |
| 12 | + packet = io.BytesIO() |
| 13 | + can = canvas.Canvas(packet, pagesize=letter) |
| 14 | + can.drawString(x, y, text) |
| 15 | + can.save() |
| 16 | + packet.seek(0) |
| 17 | + new_pdf = PyPDF2.PdfReader(packet) |
| 18 | + existing_pdf = PyPDF2.PdfReader(open(input_pdf, "rb")) |
| 19 | + writer = PyPDF2.PdfWriter() |
| 20 | + page = existing_pdf.pages[0] |
| 21 | + page.merge_page(new_pdf.pages[0]) |
| 22 | + writer.add_page(page) |
| 23 | + for p in existing_pdf.pages[1:]: |
| 24 | + writer.add_page(p) |
| 25 | + with open(output_pdf, "wb") as f: |
| 26 | + writer.write(f) |
| 27 | + |
| 28 | +# Insert image into a PDF (creates a new PDF with image overlay) |
| 29 | +def insert_image(input_pdf, output_pdf, image_path, x=100, y=500, w=200, h=150): |
| 30 | + packet = io.BytesIO() |
| 31 | + can = canvas.Canvas(packet, pagesize=letter) |
| 32 | + can.drawImage(image_path, x, y, width=w, height=h) |
| 33 | + can.save() |
| 34 | + packet.seek(0) |
| 35 | + new_pdf = PyPDF2.PdfReader(packet) |
| 36 | + existing_pdf = PyPDF2.PdfReader(open(input_pdf, "rb")) |
| 37 | + writer = PyPDF2.PdfWriter() |
| 38 | + page = existing_pdf.pages[0] |
| 39 | + page.merge_page(new_pdf.pages[0]) |
| 40 | + writer.add_page(page) |
| 41 | + for p in existing_pdf.pages[1:]: |
| 42 | + writer.add_page(p) |
| 43 | + with open(output_pdf, "wb") as f: |
| 44 | + writer.write(f) |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + # Example usage |
| 48 | + # insert_text("input.pdf", "output_text.pdf", "Hello PDF!", 100, 700) |
| 49 | + # insert_image("input.pdf", "output_image.pdf", "image.jpg", 100, 500, 200, 150) |
| 50 | + print("Simple PDF Editor ready. Uncomment example usage to test.") |
0 commit comments