Changing text color in PDF #1532
-
Hello, Is there a way the color of the font in the existing PDF can be changed? The script linked here might help. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 17 replies
-
There is no "direct" way to do this. To do it in the clean way requires rebuilding the file.
|
Beta Was this translation helpful? Give feedback.
-
The (preferred) redaction approach would go along these lines:
|
Beta Was this translation helpful? Give feedback.
-
Look at this snippet: import fitz
from pprint import pprint
text = "Kleine Schwertwale bilden Schulen"
doc = fitz.open("text-oc.pdf")
page = doc[0]
rl = page.search_for(text)
assert len(rl) == 1
clip = rl[0]
# extract text info now - before the redacting removes it.
blocks = page.get_text("dict", clip=clip)["blocks"]
span = blocks[0]["lines"][0]["spans"][0]
assert span["text"] == text
# remove text
page.add_redact_annot(clip)
page.apply_redactions()
# re-insert same text - different color
font = fitz.Font("figo") # this must be known somehow - or simply try some font else
tw = fitz.TextWriter(page.rect, color=(1, 0, 0))
# text insertion must use the original insertion poin and font size.
# if not original font, then some fontsize adjustments will probably be required:
# check bbox.width against textlength computed with new font
tw.append(span["origin"], text, font=font, fontsize=span["size"])
tw.write_text(page)
doc.ez_save("x.pdf") |
Beta Was this translation helpful? Give feedback.
-
As a courtesy 😁, here an example for a font changer: import fitz
from pprint import pprint
text = "Kleine Schwertwale bilden Schulen"
doc = fitz.open("text-oc.pdf")
page = doc[0]
rl = page.search_for(text)
assert len(rl) == 1
clip = rl[0]
blocks = page.get_text("dict", clip=clip)["blocks"]
span = blocks[0]["lines"][0]["spans"][0]
assert span["text"] == text
textbox = fitz.Rect(span["bbox"])
page.add_redact_annot(clip)
page.apply_redactions()
font = fitz.Font("cobo") # be awkward: courier bold
textlength = font.text_length(text, span["size"])
if textlength != textbox.width: # adjust fontsize where necessary
fontsize = textbox.width / textlength * span["size"]
else:
fontsize = span["size"]
tw = fitz.TextWriter(page.rect, color=(1, 0, 0))
tw.append(span["origin"], text, font=font, fontsize=fontsize)
tw.write_text(page)
doc.ez_save("x.pdf") |
Beta Was this translation helpful? Give feedback.
-
For cases other than your current concerns: |
Beta Was this translation helpful? Give feedback.
-
What does "flattened" mean in this context? |
Beta Was this translation helpful? Give feedback.
-
Hm, still no clue what flatten might mean. |
Beta Was this translation helpful? Give feedback.
Look at this snippet: