2

I would like to draw a shape such as a rectangle inside pdf. I have tried with the below code, but it is adding a text in pdf. How can I draw it?

# Add text to Existing PDF using Python

from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
TXT="Sample Text"
can.drawString(300, 70, TXT) #coordinates (x,y)
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()
BSFU
  • 59
  • 1
  • 7

1 Answers1

3

I achieved it with the library fitz (pymupdf)

import fitz
# Open the pdf
doc = fitz.open('./test.pdf')
for page in doc:
    # For every page, draw a rectangle on coordinates (1,1)(100,100)
    page.draw_rect([1,1,100,100],  color = (0, 1, 0), width = 2)
# Save pdf
doc.save('./your-route/name.pdf')
miguelik
  • 475
  • 4
  • 11