Moving Text/Rects in a PDF? #2433
-
What I want to achieve is rather simple: I want to move the position of certain text rects. These texts are always on the same position on each page, but have different texts. They need to be moved on each page. My first approach was to get the text by using the rough coordinates of the rect and try to find it by The second approach was to use Is there a better approach to solve this task? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
If the text "always has the same position", does that mean you have the rect coordinates? Going into the mud and modifying the |
Beta Was this translation helpful? Give feedback.
-
I figured that the text I wanted to move is always at the same import fitz
doc = fitz.open("pdf_in.pdf")
for page in doc:
page.clean_contents()
xref = page.get_contents()[0]
lines = page.read_contents().splitlines()
imgs = doc.get_page_images(page.number)
for i in range(len(lines)):
# Find images
if lines[i].endswith(b"Do"): # OR if b"/Im" in lines[i]:
for img in imgs:
if lines[i].decode()[1:4] in img:
print(img)
# Move text element
if lines[i].startswith(b"1 0 0 1 342"):
parts = lines[i].split()
parts[4] = str(float(parts[4].decode()) - 50).encode() # X
parts[5] = str(float(parts[5].decode()) - 40).encode() # Y
lines[i] = b" ".join(parts)
# Remove text element
elif lines[i].startswith(b"1 0 0 1 387"):
for k in range(i-1, i+6):
lines[k] = b""
doc.update_stream(xref, b"\n".join(lines))
doc.save("pdf_out.pdf")
doc.close() @JorjMcKie I'd be glad if you could leave some feedback! Especially regarding the |
Beta Was this translation helpful? Give feedback.
I figured that the text I wanted to move is always at the same
x
position and that there are no other objects on this value. I took @JorjMcKie code from #1640 (comment) and rewrote it, so that it alters the positions: