replace_object_with - alternative removal method

Some publishers generate pdfs with the watermarks inside the text of a
page, in which case the object needs to be replaced. This deflates the
object and uses plaintext instead. While this increases the size of the
pdf, it is also effective for removing watermarks from the stream.
This commit is contained in:
Bryan Bishop 2013-02-06 17:27:12 -06:00
parent 57b6aba099
commit 47bc734318
1 changed files with 35 additions and 3 deletions

View File

@ -7,21 +7,25 @@ Tools to erase things from pdfs by direct manipulation of the pdf format.
"""
def remove_object_by_id(content, objid):
def manipulate_pdf(content, objid, callback, *args):
"""
Deletes an object from a pdf. Mostly streams and FlateDecode stuff.
Iterates through a pdf looking for the object with the objid id. When the
object is found, callback is called with a reference to the current list of
output lines.
"""
outlines = []
content = content.replace("\r\n", "\n")
lines = content.split("\n")
last_line = None
skip_mode = False
for line in lines:
if not skip_mode:
if last_line in ["endobj", None]:
if last_line in ["endobj", "endobj ", None]:
if line[-3:] == "obj" or line[-4:] == "obj " or " obj<<" in line[0:50]:
if line.startswith(str(objid) + " "):
skip_mode = True
last_line = line
callback(outlines, *args)
continue
outlines.append(line)
elif skip_mode:
@ -31,3 +35,31 @@ def remove_object_by_id(content, objid):
output = "\n".join(outlines)
return output
def remove_object_by_id(content, objid):
"""
Deletes an object from a pdf. Mostly streams and FlateDecode stuff.
"""
def _remove_object(outlines): pass
output = manipulate_pdf(content, objid, _remove_object)
return output
def replace_object_with(content, objid, replacement):
"""
Replaces an object from a pdf. Mostly streams. This is useful for replacing
an encoded object with a plaintext object.
"""
def _replace_object_with(outlines, details):
objid = details["objid"]
replacement = details["replacement"]
output = str(objid) + " 0 obj\n"
output += "<</Length " + str(len(replacement)+2) + ">>stream\n"
output += replacement
output += "\nendstream\nendobj\n"
for line in output.split("\n"):
outlines.append(line)
output = manipulate_pdf(content, objid, _replace_object_with, {"objid": objid, "replacement": replacement})
return output