class RedactorOptions:
"""Redaction and I/O options."""
code
# Input/Output
input_stream = None
output_stream = None
# Metadata filters map names of entries in the PDF Document Information Dictionary
# (e.g. "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
# and "ModDate") to an array of functions to run on the values of those keys.
#
# Each function is given a pdfrw.objects.PdfString containing the current field value,
# or None if the field is not present in the input PDF, as the function's first argument
# and it must return either a string, a datetime.datetime value (CreationDate and ModDate
# should datetime.datetime values), or None to replace the field's value with. Return
# None to clear the field (unless a later function adds a new value).
#
# The functions are run in order. Each function is given the previous function's return
# value. The last function's return value is put into the output PDF.
#
# If a datetime.datetime is returned without timezone info (a "naive" datetime), then
# it must be in UTC. Use pytz.timezone.localize to encode a local time.
#
# Use "DEFAULT" as a key to apply functions to all metadata fields that have no specific
# functions defined, which is useful to remove all unrecognized fields.
#
# Use "ALL" to appy functions to all metadata fields, after any field-specific
# functions or DEFAULT functions are run.
metadata_filters = {}
# The XMP metadata filters are functions that are passed any existing XMP data and
# return new XMP metadata. The functions are called in order and each is passed the
# result of the previous function. The functions are given an xml.etree.Element object,
# or None, as their first argument and must return an object of the same type, or None.
xmp_filters = []
# This function controls how XML returned by xmp_filters is serialized. Replace this
# function with any function that takes an xml.etree.Element object and returns a string
# (a unicode string --- don't serialize to bytes).
xmp_serializer = None
# The content filters are run on the combined content streams of the pages, as well
# as on each annotation's text attributes separately.
#
# Each filter is a tuple of a compiled regular expression and a function to generate
# replacement text, which is given a re.Match object as its sole argument. It must return a string.
#
# Since spaces in PDFs are sometimes not encoded as text but instead as positional
# offsets (like newlines), the regular expression should treat all spaces as optional.
#
# Since pdfrw doesn't support content stream compression, you should use a tool like qpdf
# to decompress the streams before using this tool (see the README).
content_filters = []
# When replacement text isn't likely to have a glyph stored in the PDF's fonts,
# replace the character with these other characters (if they don't have the same
# problem):
content_replacement_glyphs = ['?', '#', '*', ' ']
# The link filters are run on link annotations. Each link filter is a function
# that is passed the link target (a string holding a URI) and a second argujment
# holding the annotation object. The function should return a new URI or None to
# remove the link.
link_filters = []
def redactor(options):
# This is the function that performs redaction.
code
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin # input stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to
from pdfrw import PdfReader, PdfWriter
# Read the PDF.
document = PdfReader(options.input_stream)
# Modify its Document Information Dictionary metadata.
update_metadata(document, options)
# Modify its XMP metadata.
update_xmp_metadata(document, options)
if options.content_filters:
# Build up the complete text stream of the PDF content.
text_layer = build_text_layer(document, options)
# Apply filters to the text stream.
update_text_layer(options, *text_layer)
# Replace page content streams with updated tokens.
apply_updated_text(document, *text_layer)
# Update annotations.
update_annotations(document, options)
# Write the PDF back out.
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
def update_metadata(trailer, options):
# Update the PDF's Document Information Dictionary, which contains keys like
# Title, Author, Subject, Keywords, Creator, Producer, CreationDate, and ModDate
# (the latter two containing Date values, the rest strings).
code
import codecs
from pdfrw.objects import PdfString, PdfName
# Create the metadata dict if it doesn't exist, since the caller may be adding fields.
if not trailer.Info:
trailer.Info = PdfDict()
# Get a list of all metadata fields that exist in the PDF plus any fields
# that there are metadata filters for (since they may insert field values).
keys = set(str(k)[1:] for k in trailer.Info.keys()) \
| set(k for k in options.metadata_filters.keys() if k not in ("DEFAULT", "ALL"))
# Update each metadata field.
for key in keys:
# Get the functions to apply to this field.
functions = options.metadata_filters.get(key)
if functions is None:
# If nothing is defined for this field, use the DEFAULT functions.
functions = options.metadata_filters.get("DEFAULT", [])
# Append the ALL functions.
functions += options.metadata_filters.get("ALL", [])
# Run the functions on any existing values.
value = trailer.Info[PdfName(key)]
for f in functions:
# Before passing to the function, convert from a PdfString to a Python string.
if isinstance(value, PdfString):
# decode from PDF's "(...)" syntax.
value = value.decode()
# Filter the value.
value = f(value)
# Convert Python data type to PdfString.
if isinstance(value, str) or (sys.version_info < (3,) and isinstance(value, unicode)):
# Convert string to a PdfString instance.
value = PdfString.from_unicode(value)
elif isinstance(value, datetime):
# Convert datetime into a PDF "D" string format.
value = value.strftime("%Y%m%d%H%M%S%z")
if len(value) == 19:
# If TZ info was included, add an apostrophe between the hour/minutes offsets.
value = value[:17] + "'" + value[17:]
value = PdfString("(D:%s)" % value)
elif value is None:
# delete the metadata value
pass
else:
raise ValueError("Invalid type of value returned by metadata_filter function. %s was returned by %s." %
(repr(value), f.__name__ or "anonymous function"))
# Replace value.
trailer.Info[PdfName(key)] = value
def update_xmp_metadata(trailer, options):
if trailer.Root.Metadata:
# Safely parse the existing XMP data.
from defusedxml.ElementTree import fromstring
value = fromstring(trailer.Root.Metadata.stream)
else:
# There is no XMP metadata in the document.
value = None
code
# Run each filter.
for f in options.xmp_filters:
value = f(value)
# Set new metadata.
if value is None:
# Clear it.
trailer.Root.Metadata = None
else:
# Serialize the XML and save it into the PDF metadata.
# Get the serializer.
serializer = options.xmp_serializer
if serializer is None:
# Use a default serializer based on xml.etree.ElementTree.tostring.
def serializer(xml_root):
import xml.etree.ElementTree
if hasattr(xml.etree.ElementTree, 'register_namespace'):
# Beginning with Python 3.2 we can define namespace prefixes.
xml.etree.ElementTree.register_namespace("xmp", "adobe:ns:meta/")
xml.etree.ElementTree.register_namespace("pdf13", "http://ns.adobe.com/pdf/1.3/")
xml.etree.ElementTree.register_namespace("xap", "http://ns.adobe.com/xap/1.0/")
xml.etree.ElementTree.register_namespace("dc", "http://purl.org/dc/elements/1.1/")
xml.etree.ElementTree.register_namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
return xml.etree.ElementTree.tostring(xml_root,
encoding='unicode' if sys.version_info >= (3, 0) else None)
# Create a fresh Metadata dictionary and serialize the XML into it.
trailer.Root.Metadata = PdfDict()
trailer.Root.Metadata.Type = "Metadata"
trailer.Root.Metadata.Subtype = "XML"
trailer.Root.Metadata.stream = serializer(value)
class InlineImage(PdfDict):
def read_data(self, tokens):
# "Unless the image uses ASCIIHexDecode or ASCII85Decode as one
# of its filters, the ID operator should be followed by a
# single white-space character, and the next character is
# interpreted as the first byte of image data.
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0],
tokens.current[0][0] + 3)
code
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
# 0: image data or trailing whitespace
# 1: E
# 2: I
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
o = ord(tokens.fdata[j])
if o == 0x0A: # \n
continue
elif o == 0x0D: # \r
continue
elif o >= 0x20 and o <= 0x7E:
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
# pdfrw's tokenizer PdfTokens does lexical analysis only. But we need
# to collapse arrays ([ .. ]) and dictionaries (<< ... >>) into single
# token entries.
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
# Is this a control token?
if token == "<<":
# begins a dictionary
stack.append((PdfDict, []))
continue
elif token == "[":
# begins an array
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
# ends a dictionary or array
constructor, content = stack.pop(-1)
if constructor == PdfDict:
# Turn flat list into key/value pairs.
content = chunk_pairs(content)
token = constructor(content)
elif token == "BI":
# begins an inline image's dictionary half
stack.append((InlineImage, []))
continue
elif token == "ID":
# divides an inline image's dictionary half and data half
constructor, content = stack[-1]
content = chunk_pairs(content)
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
# ends an inline image
token, _ = stack.pop(-1)
code
# If we're inside something, add this token to that thing.
if len(stack) > 0:
stack[-1][1].append(token)
continue
# Yield it.
yield token
def build_text_layer(document, options):
# Within each page's content stream, look for text-showing operators to
# find the text content of the page. Construct a string that contains the
# entire text content of the document AND a mapping from characters in the
# text content to tokens in the content streams. That lets us modify the
# tokens in the content streams when we find text that we want to redact.
#
# The text-showing operators are:
#
# (text) Tj -- show a string of text
# (text) ' -- move to next line and show a string of text
# aw ac (text) " -- show a string of text with word/character spacing parameters
# [ ... ] TJ -- show text strings from the array, which are interleaved with spacing parameters
#
# (These operators appear only within BT ... ET so-called "text objects",
# although we don't make use of it.)
#
# But since we don't understand any of the other content stream operators,
# and in particular we don't know how many operands each (non-text) operator
# takes, we can never be sure whether what we see in the content stream is
# an operator or an operand. If we see a "Tj", maybe it is the operand of
# some other operator?
#
# We'll assume we can get by just fine, however, assuming that whenever we
# see one of these tokens that it's an operator and not an operand.
#
# But TJ remains a little tricky because its operand is an array that preceeds
# it. Arrays are delimited by square brackets and we need to parse that.
#
# We also have to be concerned with the encoding of the text content, which
# depends on the active font. With a simple font, the text is a string whose
# bytes are glyph codes. With a composite font, a CMap maps multi-byte
# character codes to glyphs. In either case, we must map glyphs to unicode
# characters so that we can pattern match against it.
#
# To know the active font, we look for the " Tf" operator.
code
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def chunk_triples(s):
while len(s) >= 3:
yield (s.pop(0), s.pop(0), s.pop(0))
def toUnicode(string, font, fontcache):
# This is hard!
code
if not font:
# There is no font for this text. Assume Latin-1.
return string.decode("Latin-1")
elif font.ToUnicode:
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([font.ToUnicode])
# Use the CMap, which maps character codes to Unicode code points.
if font.ToUnicode.stream not in fontcache:
fontcache[font.ToUnicode.stream] = CMap(font.ToUnicode)
cmap = fontcache[font.ToUnicode.stream]
string = cmap.decode(string)
# print(string, end='', file=sys.stderr)
# sys.stderr.write(string)
return string
elif font.Encoding == "/WinAnsiEncoding":
return string.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string.decode("mac_roman", "replace")
else:
return "?"
# raise ValueError("Don't know how to decode data from font %s." % font)
def fromUnicode(string, font, fontcache, options):
# Filter out characters that are not likely to have renderable glyphs
# because the character didn't occur in the original PDF in its font.
# For any character that didn't occur in the original PDF, replace it
# with the first character in options.content_replacement_glyphs that
# did occur in the original PDF. If none ocurred, delete the character.
if font and font.BaseFont in fontcache:
char_occurs = fontcache[font.BaseFont]
code
def map_char(c):
for cc in [c] + options.content_replacement_glyphs:
if cc in char_occurs:
return cc
return "" # no replacement glyph => omit character
string = "".join(map_char(c) for c in string)
# Encode the Unicode string in the same encoding that it was originally
# stored in --- based on the font that was active when the token was
# used in a text-showing operation.
if not font:
# There was no font for this text. Assume Latin-1.
return string.encode("Latin-1")
elif font.ToUnicode and font.ToUnicode.stream in fontcache:
# Convert the Unicode code points back to one/two-byte CIDs.
cmap = fontcache[font.ToUnicode.stream]
return cmap.encode(string)
# Convert using a simple encoding.
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
# Don't know how to handle this sort of font.
else:
raise ValueError("Don't know how to encode data to font %s." % font)
def update_text_layer(options, text_tokens, page_tokens):
if len(text_tokens) == 0:
# No text content.
return
code
# Apply each regular expression to the text content...
for pattern, function in options.content_filters:
# Finding all matches...
text_tokens_index = 0
text_tokens_charpos = 0
text_tokens_token_xdiff = 0
text_content = "".join(t.value for t in text_tokens)
for m in pattern.finditer(text_content):
# We got a match at text_content[i1:i2].
i1 = m.start()
i2 = m.end()
# Pass the matched text to the replacement function to get replaced text.
replacement = function(m)
# Do a text replacement in the tokens that produced this text content.
# It may have been produced by multiple tokens, so loop until we find them all.
while i1 < i2:
# Find the original tokens in the content stream that
# produced the matched text. Start by advancing over any
# tokens that are entirely before this span of text.
while text_tokens_index < len(text_tokens) and \
text_tokens_charpos + len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff <= i1:
text_tokens_charpos += len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff
text_tokens_index += 1
text_tokens_token_xdiff = 0
if text_tokens_index == len(text_tokens): break
assert (text_tokens_charpos <= i1)
# The token at text_tokens_index, and possibly subsequent ones,
# are responsible for this text. Replace the matched content
# here with replacement content.
tok = text_tokens[text_tokens_index]
# Where does this match begin within the token's text content?
mpos = i1 - text_tokens_charpos
assert mpos >= 0
# How long is the match within this token?
mlen = min(i2 - i1, len(tok.value) - text_tokens_token_xdiff - mpos)
assert mlen >= 0
# How much should we replace here?
if mlen < (i2 - i1):
# There will be more replaced later, so take the same number
# of characters from the replacement text.
r = replacement[:mlen]
replacement = replacement[mlen:]
else:
# This is the last token in which we'll replace text, so put
# all of the remaining replacement content here.
r = replacement
replacement = None # sanity
# Do the replacement.
tok.value = tok.value[:mpos + text_tokens_token_xdiff] + r + tok.value[
mpos + mlen + text_tokens_token_xdiff:]
text_tokens_token_xdiff += len(r) - mlen
# Advance for next iteration.
i1 += mlen
def update_annotations(document, options):
for page in document.pages:
if hasattr(page, 'Annots') and isinstance(page.Annots, list):
for annotation in page.Annots:
update_annotation(annotation, options)
def update_annotation(annotation, options):
import re
from pdfrw.objects import PdfString
code
# Contents holds a plain-text representation of the annotation
# content, such as for accessibility. All annotation types may
# have a Contents. NM holds the "annotation name" which also
# could have redactable text, I suppose. Markup annotations have
# "T" fields that hold a title / text label. Subj holds a
# comment subject. CA, RC, and AC are used in widget annotations.
for string_field in ("Contents", "NM", "T", "Subj", "CA", "RC", "AC"):
if getattr(annotation, string_field):
value = getattr(annotation, string_field).to_unicode()
for pattern, function in options.content_filters:
value = pattern.sub(function, value)
setattr(annotation, string_field, PdfString.from_unicode(value))
# A rich-text stream. Not implemented. Bail so that we don't
# accidentally leak something that should be redacted.
if annotation.RC:
raise ValueError("Annotation rich-text streams (Annot/RC) are not supported.")
# An action, usually used for links.
if annotation.A:
update_annotation_action(annotation, annotation.A, options)
if annotation.PA:
update_annotation_action(annotation, annotation.PA, options)
# If set, another annotation.
if annotation.Popup:
update_annotation(annotation.Popup, options)
TODO? Redaction annotations have some other attributes that might
have text. But since they're intended for redaction... maybe we
should keep them anyway.
def update_annotation_action(annotation, action, options):
from pdfrw.objects import PdfString
code
if action.URI and options.link_filters:
value = action.URI.to_unicode()
for func in options.link_filters:
value = func(value, annotation)
if value is None:
# Remove annotation by supressing the action.
action.URI = None
else:
action.URI = PdfString.from_unicode(value)
if action.Next:
# May be an Action or array of Actions to execute next.
next_action = action.Next
if isinstance(action.Next, dict):
next_action = [action.Next]
for a in next_action:
update_annotation_action(annotation, a, options)
def apply_updated_text(document, text_tokens, page_tokens):
# Create a new content stream for each page by concatenating the
# tokens in the page_tokens lists.
from pdfrw import PdfArray
for i, page in enumerate(document.pages):
if page.Contents is None: continue # nothing was here
code
# Replace the page's content stream with our updated tokens.
# The content stream may have been an array of streams before,
# so replace the whole thing with a single new stream. Unfortunately
# the str on PdfArray and PdfDict doesn't work right.
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, InlineImage):
return "BI " + " ".join(
tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + " ID " + tok.stream + " EI "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + ">> "
return str(tok)
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream) # reset
if name == "main":
redactor(RedactorOptions())
分析一下上边代码
Assistant
这段代码实现了一个通用的 PDF 文本层级别 的“文字脱敏(redaction)”工具,使用了Python库 pdfrw 来读取、解析、修改和写回PDF文件。它工作的重点是在PDF的文本内容、元数据(Metadata)、XMP元数据以及注释(Annotations)中查找、匹配通过规则(filters)定义的敏感内容,进行替换或删除。
import io
from pdfminer.cmapdb import CMap
from pdfminer.psparser import PSStackParser
def load_cmap_from_stream(stream_data):
fp = io.BytesIO(stream_data)
parser = PSStackParser(fp)
cmap = CMap()
cmap.parse(parser)
return cmap
def decode_with_cmap(cmap, byte_string):
ret = []
i = 0
while i < len(byte_string):
maxlen = 4
for length in reversed(range(1, maxlen + 1)):
piece = byte_string[i:i + length]
char = cmap.get_unicode(piece)
if char is not None:
ret.append(char)
i += length
break
else:
ret.append("?")
i += 1
return "".join(ret)
def encode_with_cmap(cmap, string):
out = bytearray()
for ch in string:
b = cmap.get_charcode(ch)
if b is None:
continue
out.extend(b)
return bytes(out)
你出现提取后 TextToken 的 value 和 original_value 都是 "??" 的情况,说明 PDF 里的 ToUnicode 映射表没有正确生效或缺失,导致 PDF 内容流中的字节流无法映射到正确的 Unicode 字符,结果被替换成了问号。这是 PDF 中中文乱码的常见表现。具体原因及对应检查和处理建议如下:
for page in document.pages:
resources = page.Resources
if resources and hasattr(resources, 'Font'):
for font_key, font in resources.Font.items():
print(f"Font {font_key}:")
print(" ToUnicode:", hasattr(font, 'ToUnicode'), getattr(font, 'ToUnicode', None))
if not font or not hasattr(font, 'ToUnicode'):
try:
# 尝试gb18030
return string.decode('gb18030')
except:
return string.decode('latin1', errors='ignore')
import pdfplumber
import re
def redact_pdf(input_pdf_path, output_pdf_path, content_filters):
replacement_map = content_filters # list of (pattern, replacement_func)
with pdfplumber.open(input_pdf_path) as pdf:
all_texts = []
for page in pdf.pages:
text = page.extract_text()
if not text:
all_texts.append('')
continue
for pattern, func in replacement_map:
text = pattern.sub(func, text)
all_texts.append(text)
# 这里简单示范输出处理结果文本
# 因pdfplumber不支持写,需用其他库输出新PDF或再结合PyMuPDF写入
with open(output_pdf_path + '.txt', 'w', encoding='utf-8') as f:
f.write('\n\n'.join(all_texts))
print("文本提取并替换已保存为文本文件")
# 用法示范
content_filters = [
(re.compile(r"敏感词"), lambda m: "***"),
]
redact_pdf("input.pdf", "output", content_filters)
for page in document.pages:
if page.Resources and page.Resources.Font:
fonts = page.Resources.Font
for fontname in fonts:
font = fonts[fontname]
print(fontname, getattr(font, 'ToUnicode', None))
没有 ToUnicode 的字体,中文是没法正确解码的。
2. 调整toUnicode函数,确认字节流和编码转换安全
用你先前改进后的 toUnicode 核心逻辑,大致形如:
python
def toUnicode(string_bytes, font, fontcache):
if not font or not getattr(font, 'ToUnicode', None):
# Protect against missing ToUnicode: 尝试用几种编码解码
for enc in ['utf-8', 'gb18030', 'latin1']:
try:
return string_bytes.decode(enc)
except:
continue
return string_bytes.decode('latin1', errors='ignore')
stream_data = font.ToUnicode.stream
if isinstance(stream_data, str):
stream_data = stream_data.encode('latin1')
if stream_data not in fontcache:
cmap = CMap(font.ToUnicode)
fontcache[stream_data] = cmap
else:
cmap = fontcache[stream_data]
return cmap.decode_to_unicode(string_bytes)
User
print(fontname, getattr(font, 'ToUnicode', None))
结果:/F6 {'/Length': '2439'}
/F7 {'/Length': '378'}
/F8 {'/Length': '368'}
/F9 {'/Length': '368'}
print("Raw bytes:", string_bytes)
print("Decoded:", decoded_string)
结果:
Raw bytes: b'\x00\x01'
Decoded: ?
Raw bytes: b'\x00\x02'
Decoded: ?
Raw bytes: b'\x00\x03'
Decoded: ?
Raw bytes: b'\x00\x04'
Decoded: ?
Raw bytes: b'\x00\x05'
Decoded: ?
Raw bytes: b'\x00\x06'
Decoded: ?
Raw bytes: b'\x00\x07'
Decoded: ?
Raw bytes: b'\x00\x08'
Decoded: ?
Raw bytes: b'\x00\t'
Decoded: ?
Raw bytes: b'\x00\x01'
Decoded: ?
Raw bytes: b'\x00\x05'
Decoded: ?
Raw bytes: b'\x00\n'
Decoded: ?
Raw bytes: b'\x00\x0b'
Decoded: ?
Raw bytes: b'\x00\x0c'
Decoded: ?
Raw bytes: b'\x00\r'
Decoded: 堩
Raw bytes: b'\x00\x0e'
Decoded: â
Raw bytes: b'\x00\x0f'
Decoded: 亙
Raw bytes: b'\x00\x10'
Decoded: 枰
Raw bytes: b'\x00\x11'
Decoded: 疝
Raw bytes: b'\x00\x12'
Decoded: 疝
Raw bytes: b'\x00\x13'
Decoded:
Raw bytes: b'\x00\x14'
Decoded: 疝
Raw bytes: b'\x00\x15'
Decoded: i
Raw bytes: b'\x00\x0f'
Decoded: 亙
Raw bytes: b'\x00\x0e'
Decoded: â
Raw bytes: b'\x00\x10'
Decoded: 枰
Raw bytes: b'\x00\x16'
Decoded: 体
Raw bytes: b'\x00\x17'
Decoded: 雤
Raw bytes: b'\x00\x0e'
Decoded: â
Raw bytes: b'\x00\x01'
Decoded: ?
Raw bytes: b'\x00\x02'
Decoded: ?
Raw bytes: b'\x00\x18'
Decoded: ?
Raw bytes: b'\x00\x19'
Decoded: ?
Raw bytes: b'\x00\x1a'
Decoded: ?
Raw bytes: b'\x00\x1b'
Decoded: ?
Raw bytes: b'\x00\x1c'
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
Raw bytes: b'\x00\x1e'
Decoded: ?
Raw bytes: b'\x00\x1f'
Decoded: ?
Raw bytes: b'\x00\x15'
Decoded: i
Raw bytes: b'\x00 '
Decoded: ?
Raw bytes: b'\x00!'
Decoded: ?
Raw bytes: b'\x00"'
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
Raw bytes: b'\x00#'
Decoded: ?
Raw bytes: b'\x00\x1f'
Decoded: ?
Raw bytes: b'\x00\x15'
Decoded: i
Raw bytes: b'\x00$'
Decoded: 琄
Raw bytes: b'\x00%'
Decoded: 堩
Raw bytes: b'\x00&'
Decoded: ?
Raw bytes: b"\x00'"
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
Raw bytes: b'\x00\x1d'
Decoded: ?
如果需要其他调试打印信息,请详细告诉打印代码位置
Assistant
你的调试信息显示:
font.ToUnicode 是一个 PDF 对象(字典)但只包含 /Length,说明你的 PDF 字体没有内嵌有效的 ToUnicode 流,这就是大部分字符解码结果为问号 ? 的根本原因;
from pdfrw import PdfObject, PdfString, PdfArray
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
text_tokens = []
fontcache = {}
class TextToken: # 将整个类定义移动到模块顶层(如RedactorOptions下方)
value = None
font = None
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
# __str__ is used for serialization
if self.value == self.original_value:
# If unchanged, return the raw original value without decoding/encoding.
return PdfString.from_bytes(self.raw_original_value)
else:
# If the value changed, encode it from Unicode according to the encoding
# of the font that is active at the location of this token.
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
# __repr__ is used for debugging
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "": return
text_tokens.append(token)
# For each page...
page_tokens = []
for page in document.pages:
# For each token in the content stream...
# Remember this page's revised token list.
token_list = []
page_tokens.append(token_list)
if page.Contents is None:
continue
prev_token = None
prev_prev_token = None
current_font = None
# The page may have one content stream or an array of content streams.
# If an array, they are treated as if they are concatenated into a single
# stream (per the spec).
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
# If a compression Filter is applied, attempt to un-apply it. If an unrecognized
# filter is present, an error is raised. uncompress_streams expects an array of
# streams.
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
token = TextToken(token.to_bytes(), current_font)
# Remember all unicode characters seen in this font so we can
# avoid inserting characters that the PDF isn't likely to have
# a glyph for.
if current_font and current_font.BaseFont:
fontcache.setdefault(current_font.BaseFont, set()).update(token.value)
return token
# Iterate through the tokens in the page's content streams.
for token in tokenize_streams(content.stream for content in contents):
# Replace any string token with our own class that hold a mutable
# value, which is how we'll rewrite content.
token = make_mutable_string_token(token)
# Append the token into a new list that holds all tokens.
token_list.append(token)
# If the token is an operator and we're not inside an array...
if isinstance(token, PdfObject):
# And it's one that we recognize, process it.
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
# Simple text operators.
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
# The text array operator.
for i in range(len(prev_token)):
# (item may not be a string! only the strings are text.)
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
# Update the current font.
# prev_prev_token holds the font 'name'. The name must be looked up
# in the content stream's resource dictionary, which is page.Resources,
# plus any resource dictionaries above it in the document hierarchy.
current_font = None
resources = page.Resources
while resources and not current_font:
current_font = resources.Font[prev_prev_token]
resources = resources.Parent
# Remember the previously seen token in case the next operator is a text-showing
# operator -- in which case this was the operand. Remember the token before that
# because it may be a font name for the Tf operator.
prev_prev_token = prev_token
prev_token = token
return (text_tokens, page_tokens)
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([cmap])
# print(cmap.stream, file=sys.stderr)
# This is based on https://github.com/euske/pdfminer/blob/master/pdfminer/cmapdb.py.
from pdfrw import PdfString, PdfArray
in_cmap = False
operand_stack = []
codespacerange = []
def code_to_int(code):
# decode hex encoding
code = code.to_bytes()
if sys.version_info < (3,):
code = (ord(c) for c in code)
from functools import reduce
return reduce(lambda x0, x: x0 * 256 + x, (b for b in code))
def add_mapping(code, char, offset=0):
# Is this a mapping for a one-byte or two-byte character code?
width = len(codespacerange[0].to_bytes())
assert len(codespacerange[1].to_bytes()) == width
if width == 1:
# one-byte entry
if sys.version_info < (3,):
code = chr(code)
else:
code = bytes([code])
elif width == 2:
if sys.version_info < (3,):
code = chr(code // 256) + chr(code & 255)
else:
code = bytes([code // 256, code & 255])
else:
raise ValueError("Invalid code space range %s?" % repr(codespacerange))
# Some range operands take an array.
if isinstance(char, PdfArray):
char = char[offset]
# The Unicode character is given usually as a hex string of one or more
# two-byte Unicode code points.
if isinstance(char, PdfString):
char = char.to_bytes()
if sys.version_info < (3,): char = (ord(c) for c in char)
c = ""
for xh, xl in chunk_pairs(list(char)):
c += (chr if sys.version_info >= (3,) else unichr)(xh * 256 + xl)
char = c
if offset > 0:
char = char[0:-1] + (chr if sys.version_info >= (3,) else unichr)(ord(char[-1]) + offset)
else:
assert offset == 0
self.bytes_to_unicode[code] = char
self.unicode_to_bytes[char] = code
for token in tokenize_streams([cmap.stream]):
if token == "begincmap":
in_cmap = True
operand_stack[:] = []
continue
elif token == "endcmap":
in_cmap = False
continue
if not in_cmap:
continue
if token == "def":
name = operand_stack.pop(0)
value = operand_stack.pop(0)
self.defns[name] = value
elif token == "usecmap":
self.usecmap = self.pop(0)
elif token == "begincodespacerange":
operand_stack[:] = []
elif token == "endcodespacerange":
codespacerange = [operand_stack.pop(0), operand_stack.pop(0)]
elif token in ("begincidrange", "beginbfrange"):
operand_stack[:] = []
elif token in ("endcidrange", "endbfrange"):
for (code1, code2, cid_or_name1) in chunk_triples(operand_stack):
if not isinstance(code1, PdfString) or not isinstance(code2, PdfString): continue
code1 = code_to_int(code1)
code2 = code_to_int(code2)
for code in range(code1, code2 + 1):
add_mapping(code, cid_or_name1, code - code1)
operand_stack[:] = []
elif token in ("begincidchar", "beginbfchar"):
operand_stack[:] = []
elif token in ("endcidchar", "endbfchar"):
for (code, char) in chunk_pairs(operand_stack):
if not isinstance(code, PdfString): continue
add_mapping(code_to_int(code), char)
operand_stack[:] = []
elif token == "beginnotdefrange":
operand_stack[:] = []
elif token == "endnotdefrange":
operand_stack[:] = []
else:
operand_stack.append(token)
def dump(self):
for code, char in self.bytes_to_unicode.items():
print(repr(code), char)
def decode(self, string):
ret = []
i = 0;
while i < len(string):
if string[i:i + 1] in self.bytes_to_unicode:
# byte matches a single-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 1]])
i += 1
elif string[i:i + 2] in self.bytes_to_unicode:
# next two bytes matches a multi-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 2]])
i += 2
else:
ret.append("?")
i += 1
return "".join(ret)
def encode(self, string):
ret = []
for c in string:
ret.append(self.unicode_to_bytes.get(c, b""))
return b"".join(ret)
def encode_with_cmap(cmap, string):
# 字符串 -> 字节流
out = bytearray()
for ch in string:
b = cmap.get_charcode(ch)
if b is None:
# 找不到就用空,或者替换字符
continue
out.extend(b)
return bytes(out)
def fromUnicode(string, font, fontcache, options):
if not font:
return string.encode("Latin-1")
if font.ToUnicode and font.ToUnicode.stream in fontcache:
cmap = fontcache[font.ToUnicode.stream]
return encode_with_cmap(cmap, string)
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
raise ValueError("Don't know how to encode data to font %s." % font)
兼容性改写总结
在你的主代码中,导入pdfminer相关模块:
python
from pdfminer.cmap import CMap
from pdfminer.psparser import PSStackParser
def fromUnicode(string, font, fontcache, options):
if not font:
return string.encode("Latin-1")
if font.ToUnicode:
stream_data = font.ToUnicode.stream
if isinstance(stream_data, str):
stream_data = stream_data.encode('latin1')
if stream_data not in fontcache:
cmap = load_cmap_from_stream(stream_data)
fontcache[stream_data] = cmap
else:
cmap = fontcache[stream_data]
out = bytearray()
for ch in string:
b = cmap.get_charcode(ch)
if b is None:
# 可用替换字符替代,或者跳过
continue
out.extend(b)
return bytes(out)
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
else:
raise ValueError("Don't know how to encode data to font %s." % font)
class IdentityUnicodeMap(UnicodeMap):
def get_unichr(self, cid: int) -> str:
"""Interpret character id as unicode codepoint"""
log.debug("get_unichr: %r, %r", self, cid)
return chr(cid)
class FileCMap(CMap):
def add_code2cid(self, code: str, cid: int) -> None:
assert isinstance(code, str) and isinstance(cid, int), str(
(type(code), type(cid)),
)
d = self.code2cid
for c in code[:-1]:
ci = ord(c)
if ci in d:
d = cast(Dict[int, object], d[ci])
else:
t: Dict[int, object] = {}
d[ci] = t
d = t
ci = ord(code[-1])
d[ci] = cid
# A0 = non-breaking space, some weird fonts can have a collision on a cid here.
if unichr == "\u00a0" and self.cid2unichr.get(cid) == " ":
return
self.cid2unichr[cid] = unichr
class PyCMap(CMap):
def init(self, name: str, module: Any) -> None:
super().init(CMapName=name)
self.code2cid = module.CODE2CID
if module.IS_VERTICAL:
self.attrs["WMode"] = 1
class CMapNotFound(CMapError):
pass
@classmethod
def _load_data(cls, name: str) -> Any:
name = name.replace("\0", "")
filename = "%s.pickle.gz" % name
log.debug("loading: %r", name)
cmap_paths = (
os.environ.get("CMAP_PATH", "/usr/share/pdfminer/"),
os.path.join(os.path.dirname(__file__), "cmap"),
)
for directory in cmap_paths:
path = os.path.join(directory, filename)
if os.path.exists(path):
gzfile = gzip.open(path)
try:
return type(str(name), (), pickle.loads(gzfile.read()))
finally:
gzfile.close()
raise CMapDB.CMapNotFound(name)
@classmethod
def get_cmap(cls, name: str) -> CMapBase:
if name == "Identity-H":
return IdentityCMap(WMode=0)
elif name == "Identity-V":
return IdentityCMap(WMode=1)
elif name == "OneByteIdentityH":
return IdentityCMapByte(WMode=0)
elif name == "OneByteIdentityV":
return IdentityCMapByte(WMode=1)
try:
return cls._cmap_cache[name]
except KeyError:
pass
data = cls._load_data(name)
cls._cmap_cache[name] = cmap = PyCMap(name, data)
return cmap
@classmethod
def get_unicode_map(cls, name: str, vertical: bool = False) -> UnicodeMap:
try:
return cls._umap_cache[name][vertical]
except KeyError:
pass
data = cls._load_data("to-unicode-%s" % name)
cls._umap_cache[name] = [PyUnicodeMap(name, data, v) for v in (False, True)]
return cls._umap_cache[name][vertical]
class CMapParser(PSStackParser[PSKeyword]):
def init(self, cmap: CMapBase, fp: BinaryIO) -> None:
PSStackParser.init(self, fp)
self.cmap = cmap
# some ToUnicode maps don't have "begincmap" keyword.
self._in_cmap = True
self._warnings: Set[str] = set()
code
def run(self) -> None:
try:
self.nextobject()
except PSEOF:
pass
KEYWORD_BEGINCMAP = KWD(b"begincmap")
KEYWORD_ENDCMAP = KWD(b"endcmap")
KEYWORD_USECMAP = KWD(b"usecmap")
KEYWORD_DEF = KWD(b"def")
KEYWORD_BEGINCODESPACERANGE = KWD(b"begincodespacerange")
KEYWORD_ENDCODESPACERANGE = KWD(b"endcodespacerange")
KEYWORD_BEGINCIDRANGE = KWD(b"begincidrange")
KEYWORD_ENDCIDRANGE = KWD(b"endcidrange")
KEYWORD_BEGINCIDCHAR = KWD(b"begincidchar")
KEYWORD_ENDCIDCHAR = KWD(b"endcidchar")
KEYWORD_BEGINBFRANGE = KWD(b"beginbfrange")
KEYWORD_ENDBFRANGE = KWD(b"endbfrange")
KEYWORD_BEGINBFCHAR = KWD(b"beginbfchar")
KEYWORD_ENDBFCHAR = KWD(b"endbfchar")
KEYWORD_BEGINNOTDEFRANGE = KWD(b"beginnotdefrange")
KEYWORD_ENDNOTDEFRANGE = KWD(b"endnotdefrange")
def do_keyword(self, pos: int, token: PSKeyword) -> None:
"""ToUnicode CMaps
See Section 5.9.2 - ToUnicode CMaps of the PDF Reference.
"""
if token is self.KEYWORD_BEGINCMAP:
self._in_cmap = True
self.popall()
return
elif token is self.KEYWORD_ENDCMAP:
self._in_cmap = False
return
if not self._in_cmap:
return
if token is self.KEYWORD_DEF:
try:
((_, k), (_, v)) = self.pop(2)
self.cmap.set_attr(literal_name(k), v)
except PSSyntaxError:
pass
return
if token is self.KEYWORD_USECMAP:
try:
((_, cmapname),) = self.pop(1)
self.cmap.use_cmap(CMapDB.get_cmap(literal_name(cmapname)))
except PSSyntaxError:
pass
except CMapDB.CMapNotFound:
pass
return
if token is self.KEYWORD_BEGINCODESPACERANGE:
self.popall()
return
if token is self.KEYWORD_ENDCODESPACERANGE:
self.popall()
return
if token is self.KEYWORD_BEGINCIDRANGE:
self.popall()
return
if token is self.KEYWORD_ENDCIDRANGE:
objs = [obj for (__, obj) in self.popall()]
for start_byte, end_byte, cid in choplist(3, objs):
if not isinstance(start_byte, bytes):
self._warn_once("The start object of begincidrange is not a byte.")
continue
if not isinstance(end_byte, bytes):
self._warn_once("The end object of begincidrange is not a byte.")
continue
if not isinstance(cid, int):
self._warn_once("The cid object of begincidrange is not a byte.")
continue
if len(start_byte) != len(end_byte):
self._warn_once(
"The start and end byte of begincidrange have "
"different lengths.",
)
continue
start_prefix = start_byte[:-4]
end_prefix = end_byte[:-4]
if start_prefix != end_prefix:
self._warn_once(
"The prefix of the start and end byte of "
"begincidrange are not the same.",
)
continue
svar = start_byte[-4:]
evar = end_byte[-4:]
start = nunpack(svar)
end = nunpack(evar)
vlen = len(svar)
for i in range(end - start + 1):
x = start_prefix + struct.pack(">L", start + i)[-vlen:]
self.cmap.add_cid2unichr(cid + i, x)
return
if token is self.KEYWORD_BEGINCIDCHAR:
self.popall()
return
if token is self.KEYWORD_ENDCIDCHAR:
objs = [obj for (__, obj) in self.popall()]
for cid, code in choplist(2, objs):
if isinstance(code, bytes) and isinstance(cid, int):
self.cmap.add_cid2unichr(cid, code)
return
if token is self.KEYWORD_BEGINBFRANGE:
self.popall()
return
if token is self.KEYWORD_ENDBFRANGE:
objs = [obj for (__, obj) in self.popall()]
for start_byte, end_byte, code in choplist(3, objs):
if not isinstance(start_byte, bytes):
self._warn_once("The start object is not a byte.")
continue
if not isinstance(end_byte, bytes):
self._warn_once("The end object is not a byte.")
continue
if len(start_byte) != len(end_byte):
self._warn_once("The start and end byte have different lengths.")
continue
start = nunpack(start_byte)
end = nunpack(end_byte)
if isinstance(code, list):
if len(code) != end - start + 1:
self._warn_once(
"The difference between the start and end "
"offsets does not match the code length.",
)
for cid, unicode_value in zip(range(start, end + 1), code):
self.cmap.add_cid2unichr(cid, unicode_value)
else:
assert isinstance(code, bytes)
var = code[-4:]
base = nunpack(var)
prefix = code[:-4]
vlen = len(var)
for i in range(end - start + 1):
x = prefix + struct.pack(">L", base + i)[-vlen:]
self.cmap.add_cid2unichr(start + i, x)
return
if token is self.KEYWORD_BEGINBFCHAR:
self.popall()
return
if token is self.KEYWORD_ENDBFCHAR:
objs = [obj for (__, obj) in self.popall()]
for cid, code in choplist(2, objs):
if isinstance(cid, bytes) and isinstance(code, bytes):
self.cmap.add_cid2unichr(nunpack(cid), code)
return
if token is self.KEYWORD_BEGINNOTDEFRANGE:
self.popall()
return
if token is self.KEYWORD_ENDNOTDEFRANGE:
self.popall()
return
self.push((pos, token))
def _warn_once(self, msg: str) -> None:
"""Warn once for each unique message"""
if msg not in self._warnings:
self._warnings.add(msg)
base_msg = (
"Ignoring (part of) ToUnicode map because the PDF data "
"does not conform to the format. This could result in "
"(cid) values in the output. "
)
log.warning(base_msg + msg)
这是最新pdfminer.cmapdb代码,请分析后结合调整上边CMap问题
fontcache = {}
def toUnicode(string_bytes, font, fontcache):
if not font:
return string_bytes.decode("latin1")
if font.ToUnicode:
stream_data = font.ToUnicode.stream
if isinstance(stream_data, str):
stream_data = stream_data.encode('latin1')
if stream_data not in fontcache:
cmap = load_cmap_from_stream(stream_data)
fontcache[stream_data] = cmap
else:
cmap = fontcache[stream_data]
# 按最大4字节长度匹配字节串进行解码
ret = []
i = 0
while i < len(string_bytes):
for length in reversed(range(1, 5)):
piece = string_bytes[i: i + length]
chars = list(cmap.decode(piece))
if chars:
# decode 返回cid列表,通常是长度1
# 你可能要调用 UnicodeMap 对象得到实际字符
# 这里简单转 chr(cid)
try:
ch = chr(chars[0])
except Exception:
ch = '?' # fallback
ret.append(ch)
i += length
break
else:
ret.append('?')
i += 1
return ''.join(ret)
elif font.Encoding == "/WinAnsiEncoding":
return string_bytes.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string_bytes.decode("mac_roman", "replace")
else:
return "?"
def fromUnicode(string, font, fontcache, options):
if not font:
return string.encode("latin1")
if font.ToUnicode:
# 这里需要根据你的 CMap 对象实现encode映射逻辑,
# 但pdfminer原生CMap不直接提供编码反向支持,这里简单演示返回空
# 可根据需要自己实现反向映射
return b''
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
raise ValueError(f"Don't know how to encode data to font {font}")
# Input/Output
input_stream = None
output_stream = None
# Metadata filters map names of entries in the PDF Document Information Dictionary
# (e.g. "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
# and "ModDate") to an array of functions to run on the values of those keys.
#
# Each function is given a pdfrw.objects.PdfString containing the current field value,
# or None if the field is not present in the input PDF, as the function's first argument
# and it must return either a string, a datetime.datetime value (CreationDate and ModDate
# should datetime.datetime values), or None to replace the field's value with. Return
# None to clear the field (unless a later function adds a new value).
#
# The functions are run in order. Each function is given the previous function's return
# value. The last function's return value is put into the output PDF.
#
# If a datetime.datetime is returned without timezone info (a "naive" datetime), then
# it must be in UTC. Use pytz.timezone.localize to encode a local time.
#
# Use "DEFAULT" as a key to apply functions to all metadata fields that have no specific
# functions defined, which is useful to remove all unrecognized fields.
#
# Use "ALL" to appy functions to all metadata fields, after any field-specific
# functions or DEFAULT functions are run.
metadata_filters = {}
# The XMP metadata filters are functions that are passed any existing XMP data and
# return new XMP metadata. The functions are called in order and each is passed the
# result of the previous function. The functions are given an xml.etree.Element object,
# or None, as their first argument and must return an object of the same type, or None.
xmp_filters = []
# This function controls how XML returned by xmp_filters is serialized. Replace this
# function with any function that takes an xml.etree.Element object and returns a string
# (a unicode string --- don't serialize to bytes).
xmp_serializer = None
# The content filters are run on the combined content streams of the pages, as well
# as on each annotation's text attributes separately.
#
# Each filter is a tuple of a compiled regular expression and a function to generate
# replacement text, which is given a re.Match object as its sole argument. It must return a string.
#
# Since spaces in PDFs are sometimes not encoded as text but instead as positional
# offsets (like newlines), the regular expression should treat all spaces as optional.
#
# Since pdfrw doesn't support content stream compression, you should use a tool like qpdf
# to decompress the streams before using this tool (see the README).
content_filters = []
# When replacement text isn't likely to have a glyph stored in the PDF's fonts,
# replace the character with these other characters (if they don't have the same
# problem):
content_replacement_glyphs = ['?', '#', '*', ' ']
# The link filters are run on link annotations. Each link filter is a function
# that is passed the link target (a string holding a URI) and a second argujment
# holding the annotation object. The function should return a new URI or None to
# remove the link.
link_filters = []
def redactor(options):
# This is the function that performs redaction.
code
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin # input stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to
from pdfrw import PdfReader, PdfWriter
# Read the PDF.
document = PdfReader(options.input_stream)
# Modify its Document Information Dictionary metadata.
update_metadata(document, options)
# Modify its XMP metadata.
update_xmp_metadata(document, options)
if options.content_filters:
# Build up the complete text stream of the PDF content.
text_layer = build_text_layer(document, options)
# Apply filters to the text stream.
update_text_layer(options, *text_layer)
# Replace page content streams with updated tokens.
apply_updated_text(document, *text_layer)
# Update annotations.
update_annotations(document, options)
# Write the PDF back out.
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
def update_metadata(trailer, options):
# Update the PDF's Document Information Dictionary, which contains keys like
# Title, Author, Subject, Keywords, Creator, Producer, CreationDate, and ModDate
# (the latter two containing Date values, the rest strings).
code
import codecs
from pdfrw.objects import PdfString, PdfName
# Create the metadata dict if it doesn't exist, since the caller may be adding fields.
if not trailer.Info:
trailer.Info = PdfDict()
# Get a list of all metadata fields that exist in the PDF plus any fields
# that there are metadata filters for (since they may insert field values).
keys = set(str(k)[1:] for k in trailer.Info.keys()) \
| set(k for k in options.metadata_filters.keys() if k not in ("DEFAULT", "ALL"))
# Update each metadata field.
for key in keys:
# Get the functions to apply to this field.
functions = options.metadata_filters.get(key)
if functions is None:
# If nothing is defined for this field, use the DEFAULT functions.
functions = options.metadata_filters.get("DEFAULT", [])
# Append the ALL functions.
functions += options.metadata_filters.get("ALL", [])
# Run the functions on any existing values.
value = trailer.Info[PdfName(key)]
for f in functions:
# Before passing to the function, convert from a PdfString to a Python string.
if isinstance(value, PdfString):
# decode from PDF's "(...)" syntax.
value = value.decode()
# Filter the value.
value = f(value)
# Convert Python data type to PdfString.
if isinstance(value, str) or (sys.version_info < (3,) and isinstance(value, unicode)):
# Convert string to a PdfString instance.
value = PdfString.from_unicode(value)
elif isinstance(value, datetime):
# Convert datetime into a PDF "D" string format.
value = value.strftime("%Y%m%d%H%M%S%z")
if len(value) == 19:
# If TZ info was included, add an apostrophe between the hour/minutes offsets.
value = value[:17] + "'" + value[17:]
value = PdfString("(D:%s)" % value)
elif value is None:
# delete the metadata value
pass
else:
raise ValueError("Invalid type of value returned by metadata_filter function. %s was returned by %s." %
(repr(value), f.__name__ or "anonymous function"))
# Replace value.
trailer.Info[PdfName(key)] = value
def update_xmp_metadata(trailer, options):
if trailer.Root.Metadata:
# Safely parse the existing XMP data.
from defusedxml.ElementTree import fromstring
value = fromstring(trailer.Root.Metadata.stream)
else:
# There is no XMP metadata in the document.
value = None
code
# Run each filter.
for f in options.xmp_filters:
value = f(value)
# Set new metadata.
if value is None:
# Clear it.
trailer.Root.Metadata = None
else:
# Serialize the XML and save it into the PDF metadata.
# Get the serializer.
serializer = options.xmp_serializer
if serializer is None:
# Use a default serializer based on xml.etree.ElementTree.tostring.
def serializer(xml_root):
import xml.etree.ElementTree
if hasattr(xml.etree.ElementTree, 'register_namespace'):
# Beginning with Python 3.2 we can define namespace prefixes.
xml.etree.ElementTree.register_namespace("xmp", "adobe:ns:meta/")
xml.etree.ElementTree.register_namespace("pdf13", "http://ns.adobe.com/pdf/1.3/")
xml.etree.ElementTree.register_namespace("xap", "http://ns.adobe.com/xap/1.0/")
xml.etree.ElementTree.register_namespace("dc", "http://purl.org/dc/elements/1.1/")
xml.etree.ElementTree.register_namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
return xml.etree.ElementTree.tostring(xml_root,
encoding='unicode' if sys.version_info >= (3, 0) else None)
# Create a fresh Metadata dictionary and serialize the XML into it.
trailer.Root.Metadata = PdfDict()
trailer.Root.Metadata.Type = "Metadata"
trailer.Root.Metadata.Subtype = "XML"
trailer.Root.Metadata.stream = serializer(value)
class InlineImage(PdfDict):
def read_data(self, tokens):
# "Unless the image uses ASCIIHexDecode or ASCII85Decode as one
# of its filters, the ID operator should be followed by a
# single white-space character, and the next character is
# interpreted as the first byte of image data.
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0],
tokens.current[0][0] + 3)
code
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
# 0: image data or trailing whitespace
# 1: E
# 2: I
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
o = ord(tokens.fdata[j])
if o == 0x0A: # \n
continue
elif o == 0x0D: # \r
continue
elif o >= 0x20 and o <= 0x7E:
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
# pdfrw's tokenizer PdfTokens does lexical analysis only. But we need
# to collapse arrays ([ .. ]) and dictionaries (<< ... >>) into single
# token entries.
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
# Is this a control token?
if token == "<<":
# begins a dictionary
stack.append((PdfDict, []))
continue
elif token == "[":
# begins an array
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
# ends a dictionary or array
constructor, content = stack.pop(-1)
if constructor == PdfDict:
# Turn flat list into key/value pairs.
content = chunk_pairs(content)
token = constructor(content)
elif token == "BI":
# begins an inline image's dictionary half
stack.append((InlineImage, []))
continue
elif token == "ID":
# divides an inline image's dictionary half and data half
constructor, content = stack[-1]
content = chunk_pairs(content)
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
# ends an inline image
token, _ = stack.pop(-1)
code
# If we're inside something, add this token to that thing.
if len(stack) > 0:
stack[-1][1].append(token)
continue
# Yield it.
yield token
def build_text_layer(document, options):
# Within each page's content stream, look for text-showing operators to
# find the text content of the page. Construct a string that contains the
# entire text content of the document AND a mapping from characters in the
# text content to tokens in the content streams. That lets us modify the
# tokens in the content streams when we find text that we want to redact.
#
# The text-showing operators are:
#
# (text) Tj -- show a string of text
# (text) ' -- move to next line and show a string of text
# aw ac (text) " -- show a string of text with word/character spacing parameters
# [ ... ] TJ -- show text strings from the array, which are interleaved with spacing parameters
#
# (These operators appear only within BT ... ET so-called "text objects",
# although we don't make use of it.)
#
# But since we don't understand any of the other content stream operators,
# and in particular we don't know how many operands each (non-text) operator
# takes, we can never be sure whether what we see in the content stream is
# an operator or an operand. If we see a "Tj", maybe it is the operand of
# some other operator?
#
# We'll assume we can get by just fine, however, assuming that whenever we
# see one of these tokens that it's an operator and not an operand.
#
# But TJ remains a little tricky because its operand is an array that preceeds
# it. Arrays are delimited by square brackets and we need to parse that.
#
# We also have to be concerned with the encoding of the text content, which
# depends on the active font. With a simple font, the text is a string whose
# bytes are glyph codes. With a composite font, a CMap maps multi-byte
# character codes to glyphs. In either case, we must map glyphs to unicode
# characters so that we can pattern match against it.
#
# To know the active font, we look for the " Tf" operator.
code
from pdfrw import PdfObject, PdfString, PdfArray
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
text_tokens = []
fontcache = {}
class TextToken: # 将整个类定义移动到模块顶层(如RedactorOptions下方)
value = None
font = None
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
# __str__ is used for serialization
if self.value == self.original_value:
# If unchanged, return the raw original value without decoding/encoding.
return PdfString.from_bytes(self.raw_original_value)
else:
# If the value changed, encode it from Unicode according to the encoding
# of the font that is active at the location of this token.
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
# __repr__ is used for debugging
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "": return
text_tokens.append(token)
# For each page...
page_tokens = []
for page in document.pages:
# For each token in the content stream...
# Remember this page's revised token list.
token_list = []
page_tokens.append(token_list)
if page.Contents is None:
continue
prev_token = None
prev_prev_token = None
current_font = None
# The page may have one content stream or an array of content streams.
# If an array, they are treated as if they are concatenated into a single
# stream (per the spec).
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
# If a compression Filter is applied, attempt to un-apply it. If an unrecognized
# filter is present, an error is raised. uncompress_streams expects an array of
# streams.
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
token = TextToken(token.to_bytes(), current_font)
# Remember all unicode characters seen in this font so we can
# avoid inserting characters that the PDF isn't likely to have
# a glyph for.
if current_font and current_font.BaseFont:
fontcache.setdefault(current_font.BaseFont, set()).update(token.value)
return token
# Iterate through the tokens in the page's content streams.
for token in tokenize_streams(content.stream for content in contents):
# Replace any string token with our own class that hold a mutable
# value, which is how we'll rewrite content.
token = make_mutable_string_token(token)
# Append the token into a new list that holds all tokens.
token_list.append(token)
# If the token is an operator and we're not inside an array...
if isinstance(token, PdfObject):
# And it's one that we recognize, process it.
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
# Simple text operators.
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
# The text array operator.
for i in range(len(prev_token)):
# (item may not be a string! only the strings are text.)
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
# Update the current font.
# prev_prev_token holds the font 'name'. The name must be looked up
# in the content stream's resource dictionary, which is page.Resources,
# plus any resource dictionaries above it in the document hierarchy.
current_font = None
resources = page.Resources
while resources and not current_font:
current_font = resources.Font[prev_prev_token]
resources = resources.Parent
# Remember the previously seen token in case the next operator is a text-showing
# operator -- in which case this was the operand. Remember the token before that
# because it may be a font name for the Tf operator.
prev_prev_token = prev_token
prev_token = token
return (text_tokens, page_tokens)
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def chunk_triples(s):
while len(s) >= 3:
yield (s.pop(0), s.pop(0), s.pop(0))
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([cmap])
# print(cmap.stream, file=sys.stderr)
# This is based on https://github.com/euske/pdfminer/blob/master/pdfminer/cmapdb.py.
from pdfrw import PdfString, PdfArray
in_cmap = False
operand_stack = []
codespacerange = []
def code_to_int(code):
# decode hex encoding
code = code.to_bytes()
if sys.version_info < (3,):
code = (ord(c) for c in code)
from functools import reduce
return reduce(lambda x0, x: x0 * 256 + x, (b for b in code))
def add_mapping(code, char, offset=0):
# Is this a mapping for a one-byte or two-byte character code?
width = len(codespacerange[0].to_bytes())
assert len(codespacerange[1].to_bytes()) == width
if width == 1:
# one-byte entry
if sys.version_info < (3,):
code = chr(code)
else:
code = bytes([code])
elif width == 2:
if sys.version_info < (3,):
code = chr(code // 256) + chr(code & 255)
else:
code = bytes([code // 256, code & 255])
else:
raise ValueError("Invalid code space range %s?" % repr(codespacerange))
# Some range operands take an array.
if isinstance(char, PdfArray):
char = char[offset]
# The Unicode character is given usually as a hex string of one or more
# two-byte Unicode code points.
if isinstance(char, PdfString):
char = char.to_bytes()
if sys.version_info < (3,): char = (ord(c) for c in char)
c = ""
for xh, xl in chunk_pairs(list(char)):
c += (chr if sys.version_info >= (3,) else unichr)(xh * 256 + xl)
char = c
if offset > 0:
char = char[0:-1] + (chr if sys.version_info >= (3,) else unichr)(ord(char[-1]) + offset)
else:
assert offset == 0
self.bytes_to_unicode[code] = char
self.unicode_to_bytes[char] = code
for token in tokenize_streams([cmap.stream]):
if token == "begincmap":
in_cmap = True
operand_stack[:] = []
continue
elif token == "endcmap":
in_cmap = False
continue
if not in_cmap:
continue
if token == "def":
name = operand_stack.pop(0)
value = operand_stack.pop(0)
self.defns[name] = value
elif token == "usecmap":
self.usecmap = self.pop(0)
elif token == "begincodespacerange":
operand_stack[:] = []
elif token == "endcodespacerange":
codespacerange = [operand_stack.pop(0), operand_stack.pop(0)]
elif token in ("begincidrange", "beginbfrange"):
operand_stack[:] = []
elif token in ("endcidrange", "endbfrange"):
for (code1, code2, cid_or_name1) in chunk_triples(operand_stack):
if not isinstance(code1, PdfString) or not isinstance(code2, PdfString): continue
code1 = code_to_int(code1)
code2 = code_to_int(code2)
for code in range(code1, code2 + 1):
add_mapping(code, cid_or_name1, code - code1)
operand_stack[:] = []
elif token in ("begincidchar", "beginbfchar"):
operand_stack[:] = []
elif token in ("endcidchar", "endbfchar"):
for (code, char) in chunk_pairs(operand_stack):
if not isinstance(code, PdfString): continue
add_mapping(code_to_int(code), char)
operand_stack[:] = []
elif token == "beginnotdefrange":
operand_stack[:] = []
elif token == "endnotdefrange":
operand_stack[:] = []
else:
operand_stack.append(token)
def dump(self):
for code, char in self.bytes_to_unicode.items():
print(repr(code), char)
def decode(self, string):
ret = []
i = 0;
while i < len(string):
if string[i:i + 1] in self.bytes_to_unicode:
# byte matches a single-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 1]])
i += 1
elif string[i:i + 2] in self.bytes_to_unicode:
# next two bytes matches a multi-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 2]])
i += 2
else:
ret.append("?")
i += 1
return "".join(ret)
def encode(self, string):
ret = []
for c in string:
ret.append(self.unicode_to_bytes.get(c, b""))
return b"".join(ret)
def toUnicode(string, font, fontcache):
# This is hard!
code
if not font:
# There is no font for this text. Assume Latin-1.
return string.decode("Latin-1")
elif font.ToUnicode:
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([font.ToUnicode])
# Use the CMap, which maps character codes to Unicode code points.
if font.ToUnicode.stream not in fontcache:
fontcache[font.ToUnicode.stream] = CMap(font.ToUnicode)
cmap = fontcache[font.ToUnicode.stream]
string = cmap.decode(string)
# print(string, end='', file=sys.stderr)
# sys.stderr.write(string)
return string
elif font.Encoding == "/WinAnsiEncoding":
return string.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string.decode("mac_roman", "replace")
else:
return "?"
# raise ValueError("Don't know how to decode data from font %s." % font)
def fromUnicode(string, font, fontcache, options):
# Filter out characters that are not likely to have renderable glyphs
# because the character didn't occur in the original PDF in its font.
# For any character that didn't occur in the original PDF, replace it
# with the first character in options.content_replacement_glyphs that
# did occur in the original PDF. If none ocurred, delete the character.
if font and font.BaseFont in fontcache:
char_occurs = fontcache[font.BaseFont]
code
def map_char(c):
for cc in [c] + options.content_replacement_glyphs:
if cc in char_occurs:
return cc
return "" # no replacement glyph => omit character
string = "".join(map_char(c) for c in string)
# Encode the Unicode string in the same encoding that it was originally
# stored in --- based on the font that was active when the token was
# used in a text-showing operation.
if not font:
# There was no font for this text. Assume Latin-1.
return string.encode("Latin-1")
elif font.ToUnicode and font.ToUnicode.stream in fontcache:
# Convert the Unicode code points back to one/two-byte CIDs.
cmap = fontcache[font.ToUnicode.stream]
return cmap.encode(string)
# Convert using a simple encoding.
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
# Don't know how to handle this sort of font.
else:
raise ValueError("Don't know how to encode data to font %s." % font)
def update_text_layer(options, text_tokens, page_tokens):
if len(text_tokens) == 0:
# No text content.
return
code
# Apply each regular expression to the text content...
for pattern, function in options.content_filters:
# Finding all matches...
text_tokens_index = 0
text_tokens_charpos = 0
text_tokens_token_xdiff = 0
text_content = "".join(t.value for t in text_tokens)
for m in pattern.finditer(text_content):
# We got a match at text_content[i1:i2].
i1 = m.start()
i2 = m.end()
# Pass the matched text to the replacement function to get replaced text.
replacement = function(m)
# Do a text replacement in the tokens that produced this text content.
# It may have been produced by multiple tokens, so loop until we find them all.
while i1 < i2:
# Find the original tokens in the content stream that
# produced the matched text. Start by advancing over any
# tokens that are entirely before this span of text.
while text_tokens_index < len(text_tokens) and \
text_tokens_charpos + len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff <= i1:
text_tokens_charpos += len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff
text_tokens_index += 1
text_tokens_token_xdiff = 0
if text_tokens_index == len(text_tokens): break
assert (text_tokens_charpos <= i1)
# The token at text_tokens_index, and possibly subsequent ones,
# are responsible for this text. Replace the matched content
# here with replacement content.
tok = text_tokens[text_tokens_index]
# Where does this match begin within the token's text content?
mpos = i1 - text_tokens_charpos
assert mpos >= 0
# How long is the match within this token?
mlen = min(i2 - i1, len(tok.value) - text_tokens_token_xdiff - mpos)
assert mlen >= 0
# How much should we replace here?
if mlen < (i2 - i1):
# There will be more replaced later, so take the same number
# of characters from the replacement text.
r = replacement[:mlen]
replacement = replacement[mlen:]
else:
# This is the last token in which we'll replace text, so put
# all of the remaining replacement content here.
r = replacement
replacement = None # sanity
# Do the replacement.
tok.value = tok.value[:mpos + text_tokens_token_xdiff] + r + tok.value[
mpos + mlen + text_tokens_token_xdiff:]
text_tokens_token_xdiff += len(r) - mlen
# Advance for next iteration.
i1 += mlen
def update_annotations(document, options):
for page in document.pages:
if hasattr(page, 'Annots') and isinstance(page.Annots, list):
for annotation in page.Annots:
update_annotation(annotation, options)
def update_annotation(annotation, options):
import re
from pdfrw.objects import PdfString
code
# Contents holds a plain-text representation of the annotation
# content, such as for accessibility. All annotation types may
# have a Contents. NM holds the "annotation name" which also
# could have redactable text, I suppose. Markup annotations have
# "T" fields that hold a title / text label. Subj holds a
# comment subject. CA, RC, and AC are used in widget annotations.
for string_field in ("Contents", "NM", "T", "Subj", "CA", "RC", "AC"):
if getattr(annotation, string_field):
value = getattr(annotation, string_field).to_unicode()
for pattern, function in options.content_filters:
value = pattern.sub(function, value)
setattr(annotation, string_field, PdfString.from_unicode(value))
# A rich-text stream. Not implemented. Bail so that we don't
# accidentally leak something that should be redacted.
if annotation.RC:
raise ValueError("Annotation rich-text streams (Annot/RC) are not supported.")
# An action, usually used for links.
if annotation.A:
update_annotation_action(annotation, annotation.A, options)
if annotation.PA:
update_annotation_action(annotation, annotation.PA, options)
# If set, another annotation.
if annotation.Popup:
update_annotation(annotation.Popup, options)
TODO? Redaction annotations have some other attributes that might
have text. But since they're intended for redaction... maybe we
should keep them anyway.
def update_annotation_action(annotation, action, options):
from pdfrw.objects import PdfString
code
if action.URI and options.link_filters:
value = action.URI.to_unicode()
for func in options.link_filters:
value = func(value, annotation)
if value is None:
# Remove annotation by supressing the action.
action.URI = None
else:
action.URI = PdfString.from_unicode(value)
if action.Next:
# May be an Action or array of Actions to execute next.
next_action = action.Next
if isinstance(action.Next, dict):
next_action = [action.Next]
for a in next_action:
update_annotation_action(annotation, a, options)
def apply_updated_text(document, text_tokens, page_tokens):
# Create a new content stream for each page by concatenating the
# tokens in the page_tokens lists.
from pdfrw import PdfArray
for i, page in enumerate(document.pages):
if page.Contents is None: continue # nothing was here
code
# Replace the page's content stream with our updated tokens.
# The content stream may have been an array of streams before,
# so replace the whole thing with a single new stream. Unfortunately
# the str on PdfArray and PdfDict doesn't work right.
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, InlineImage):
return "BI " + " ".join(
tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + " ID " + tok.stream + " EI "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + ">> "
return str(tok)
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream) # reset
if name == "main":
redactor(RedactorOptions())
之前的代码,请结合调整
def toUnicode(string_bytes, font, fontcache):
if not font or not getattr(font, 'ToUnicode', None):
try:
return string_bytes.decode('latin1')
except Exception:
return string_bytes.decode('utf-8', errors='ignore')
stream_data = font.ToUnicode.stream
if isinstance(stream_data, str):
stream_data = stream_data.encode('latin1')
if stream_data not in fontcache:
cmap, unicodemap = load_cmap_and_unicodemap_from_stream(stream_data)
fontcache[stream_data] = (cmap, unicodemap)
else:
cmap, unicodemap = fontcache[stream_data]
ret = []
i = 0
while i < len(string_bytes):
for length in reversed(range(1, 5)):
piece = string_bytes[i:i+length]
cids = list(cmap.decode(piece))
if cids:
try:
chs = [unicodemap.get_unichr(cid) for cid in cids]
except Exception:
chs = ['?'] * len(cids)
ret.extend(chs)
i += length
break
else:
ret.append('?')
i += 1
return ''.join(ret)
# Input/Output
input_stream = None
output_stream = None
# Metadata filters map names of entries in the PDF Document Information Dictionary
# (e.g. "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
# and "ModDate") to an array of functions to run on the values of those keys.
#
# Each function is given a pdfrw.objects.PdfString containing the current field value,
# or None if the field is not present in the input PDF, as the function's first argument
# and it must return either a string, a datetime.datetime value (CreationDate and ModDate
# should datetime.datetime values), or None to replace the field's value with. Return
# None to clear the field (unless a later function adds a new value).
#
# The functions are run in order. Each function is given the previous function's return
# value. The last function's return value is put into the output PDF.
#
# If a datetime.datetime is returned without timezone info (a "naive" datetime), then
# it must be in UTC. Use pytz.timezone.localize to encode a local time.
#
# Use "DEFAULT" as a key to apply functions to all metadata fields that have no specific
# functions defined, which is useful to remove all unrecognized fields.
#
# Use "ALL" to appy functions to all metadata fields, after any field-specific
# functions or DEFAULT functions are run.
metadata_filters = {}
# The XMP metadata filters are functions that are passed any existing XMP data and
# return new XMP metadata. The functions are called in order and each is passed the
# result of the previous function. The functions are given an xml.etree.Element object,
# or None, as their first argument and must return an object of the same type, or None.
xmp_filters = []
# This function controls how XML returned by xmp_filters is serialized. Replace this
# function with any function that takes an xml.etree.Element object and returns a string
# (a unicode string --- don't serialize to bytes).
xmp_serializer = None
# The content filters are run on the combined content streams of the pages, as well
# as on each annotation's text attributes separately.
#
# Each filter is a tuple of a compiled regular expression and a function to generate
# replacement text, which is given a re.Match object as its sole argument. It must return a string.
#
# Since spaces in PDFs are sometimes not encoded as text but instead as positional
# offsets (like newlines), the regular expression should treat all spaces as optional.
#
# Since pdfrw doesn't support content stream compression, you should use a tool like qpdf
# to decompress the streams before using this tool (see the README).
content_filters = []
# When replacement text isn't likely to have a glyph stored in the PDF's fonts,
# replace the character with these other characters (if they don't have the same
# problem):
content_replacement_glyphs = ['?', '#', '*', ' ']
# The link filters are run on link annotations. Each link filter is a function
# that is passed the link target (a string holding a URI) and a second argujment
# holding the annotation object. The function should return a new URI or None to
# remove the link.
link_filters = []
def redactor(options):
# This is the function that performs redaction.
code
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin # input stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to
from pdfrw import PdfReader, PdfWriter
# Read the PDF.
document = PdfReader(options.input_stream)
# Modify its Document Information Dictionary metadata.
update_metadata(document, options)
# Modify its XMP metadata.
update_xmp_metadata(document, options)
if options.content_filters:
# Build up the complete text stream of the PDF content.
text_layer = build_text_layer(document, options)
# Apply filters to the text stream.
update_text_layer(options, *text_layer)
# Replace page content streams with updated tokens.
apply_updated_text(document, *text_layer)
# Update annotations.
update_annotations(document, options)
# Write the PDF back out.
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
def update_metadata(trailer, options):
# Update the PDF's Document Information Dictionary, which contains keys like
# Title, Author, Subject, Keywords, Creator, Producer, CreationDate, and ModDate
# (the latter two containing Date values, the rest strings).
code
import codecs
from pdfrw.objects import PdfString, PdfName
# Create the metadata dict if it doesn't exist, since the caller may be adding fields.
if not trailer.Info:
trailer.Info = PdfDict()
# Get a list of all metadata fields that exist in the PDF plus any fields
# that there are metadata filters for (since they may insert field values).
keys = set(str(k)[1:] for k in trailer.Info.keys()) \
| set(k for k in options.metadata_filters.keys() if k not in ("DEFAULT", "ALL"))
# Update each metadata field.
for key in keys:
# Get the functions to apply to this field.
functions = options.metadata_filters.get(key)
if functions is None:
# If nothing is defined for this field, use the DEFAULT functions.
functions = options.metadata_filters.get("DEFAULT", [])
# Append the ALL functions.
functions += options.metadata_filters.get("ALL", [])
# Run the functions on any existing values.
value = trailer.Info[PdfName(key)]
for f in functions:
# Before passing to the function, convert from a PdfString to a Python string.
if isinstance(value, PdfString):
# decode from PDF's "(...)" syntax.
value = value.decode()
# Filter the value.
value = f(value)
# Convert Python data type to PdfString.
if isinstance(value, str) or (sys.version_info < (3,) and isinstance(value, unicode)):
# Convert string to a PdfString instance.
value = PdfString.from_unicode(value)
elif isinstance(value, datetime):
# Convert datetime into a PDF "D" string format.
value = value.strftime("%Y%m%d%H%M%S%z")
if len(value) == 19:
# If TZ info was included, add an apostrophe between the hour/minutes offsets.
value = value[:17] + "'" + value[17:]
value = PdfString("(D:%s)" % value)
elif value is None:
# delete the metadata value
pass
else:
raise ValueError("Invalid type of value returned by metadata_filter function. %s was returned by %s." %
(repr(value), f.__name__ or "anonymous function"))
# Replace value.
trailer.Info[PdfName(key)] = value
def update_xmp_metadata(trailer, options):
if trailer.Root.Metadata:
# Safely parse the existing XMP data.
from defusedxml.ElementTree import fromstring
value = fromstring(trailer.Root.Metadata.stream)
else:
# There is no XMP metadata in the document.
value = None
code
# Run each filter.
for f in options.xmp_filters:
value = f(value)
# Set new metadata.
if value is None:
# Clear it.
trailer.Root.Metadata = None
else:
# Serialize the XML and save it into the PDF metadata.
# Get the serializer.
serializer = options.xmp_serializer
if serializer is None:
# Use a default serializer based on xml.etree.ElementTree.tostring.
def serializer(xml_root):
import xml.etree.ElementTree
if hasattr(xml.etree.ElementTree, 'register_namespace'):
# Beginning with Python 3.2 we can define namespace prefixes.
xml.etree.ElementTree.register_namespace("xmp", "adobe:ns:meta/")
xml.etree.ElementTree.register_namespace("pdf13", "http://ns.adobe.com/pdf/1.3/")
xml.etree.ElementTree.register_namespace("xap", "http://ns.adobe.com/xap/1.0/")
xml.etree.ElementTree.register_namespace("dc", "http://purl.org/dc/elements/1.1/")
xml.etree.ElementTree.register_namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
return xml.etree.ElementTree.tostring(xml_root,
encoding='unicode' if sys.version_info >= (3, 0) else None)
# Create a fresh Metadata dictionary and serialize the XML into it.
trailer.Root.Metadata = PdfDict()
trailer.Root.Metadata.Type = "Metadata"
trailer.Root.Metadata.Subtype = "XML"
trailer.Root.Metadata.stream = serializer(value)
class InlineImage(PdfDict):
def read_data(self, tokens):
# "Unless the image uses ASCIIHexDecode or ASCII85Decode as one
# of its filters, the ID operator should be followed by a
# single white-space character, and the next character is
# interpreted as the first byte of image data.
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0],
tokens.current[0][0] + 3)
code
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
# 0: image data or trailing whitespace
# 1: E
# 2: I
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
o = ord(tokens.fdata[j])
if o == 0x0A: # \n
continue
elif o == 0x0D: # \r
continue
elif o >= 0x20 and o <= 0x7E:
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
# pdfrw's tokenizer PdfTokens does lexical analysis only. But we need
# to collapse arrays ([ .. ]) and dictionaries (<< ... >>) into single
# token entries.
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
# Is this a control token?
if token == "<<":
# begins a dictionary
stack.append((PdfDict, []))
continue
elif token == "[":
# begins an array
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
# ends a dictionary or array
constructor, content = stack.pop(-1)
if constructor == PdfDict:
# Turn flat list into key/value pairs.
content = chunk_pairs(content)
token = constructor(content)
elif token == "BI":
# begins an inline image's dictionary half
stack.append((InlineImage, []))
continue
elif token == "ID":
# divides an inline image's dictionary half and data half
constructor, content = stack[-1]
content = chunk_pairs(content)
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
# ends an inline image
token, _ = stack.pop(-1)
code
# If we're inside something, add this token to that thing.
if len(stack) > 0:
stack[-1][1].append(token)
continue
# Yield it.
yield token
def build_text_layer(document, options):
# Within each page's content stream, look for text-showing operators to
# find the text content of the page. Construct a string that contains the
# entire text content of the document AND a mapping from characters in the
# text content to tokens in the content streams. That lets us modify the
# tokens in the content streams when we find text that we want to redact.
#
# The text-showing operators are:
#
# (text) Tj -- show a string of text
# (text) ' -- move to next line and show a string of text
# aw ac (text) " -- show a string of text with word/character spacing parameters
# [ ... ] TJ -- show text strings from the array, which are interleaved with spacing parameters
#
# (These operators appear only within BT ... ET so-called "text objects",
# although we don't make use of it.)
#
# But since we don't understand any of the other content stream operators,
# and in particular we don't know how many operands each (non-text) operator
# takes, we can never be sure whether what we see in the content stream is
# an operator or an operand. If we see a "Tj", maybe it is the operand of
# some other operator?
#
# We'll assume we can get by just fine, however, assuming that whenever we
# see one of these tokens that it's an operator and not an operand.
#
# But TJ remains a little tricky because its operand is an array that preceeds
# it. Arrays are delimited by square brackets and we need to parse that.
#
# We also have to be concerned with the encoding of the text content, which
# depends on the active font. With a simple font, the text is a string whose
# bytes are glyph codes. With a composite font, a CMap maps multi-byte
# character codes to glyphs. In either case, we must map glyphs to unicode
# characters so that we can pattern match against it.
#
# To know the active font, we look for the " Tf" operator.
code
from pdfrw import PdfObject, PdfString, PdfArray
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
text_tokens = []
fontcache = {}
class TextToken: # 将整个类定义移动到模块顶层(如RedactorOptions下方)
value = None
font = None
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
# __str__ is used for serialization
if self.value == self.original_value:
# If unchanged, return the raw original value without decoding/encoding.
return PdfString.from_bytes(self.raw_original_value)
else:
# If the value changed, encode it from Unicode according to the encoding
# of the font that is active at the location of this token.
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
# __repr__ is used for debugging
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "": return
text_tokens.append(token)
# For each page...
page_tokens = []
for page in document.pages:
# For each token in the content stream...
# Remember this page's revised token list.
token_list = []
page_tokens.append(token_list)
if page.Contents is None:
continue
prev_token = None
prev_prev_token = None
current_font = None
# The page may have one content stream or an array of content streams.
# If an array, they are treated as if they are concatenated into a single
# stream (per the spec).
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
# If a compression Filter is applied, attempt to un-apply it. If an unrecognized
# filter is present, an error is raised. uncompress_streams expects an array of
# streams.
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
token = TextToken(token.to_bytes(), current_font)
# Remember all unicode characters seen in this font so we can
# avoid inserting characters that the PDF isn't likely to have
# a glyph for.
if current_font and current_font.BaseFont:
fontcache.setdefault(current_font.BaseFont, set()).update(token.value)
return token
# Iterate through the tokens in the page's content streams.
for token in tokenize_streams(content.stream for content in contents):
# Replace any string token with our own class that hold a mutable
# value, which is how we'll rewrite content.
token = make_mutable_string_token(token)
# Append the token into a new list that holds all tokens.
token_list.append(token)
# If the token is an operator and we're not inside an array...
if isinstance(token, PdfObject):
# And it's one that we recognize, process it.
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
# Simple text operators.
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
# The text array operator.
for i in range(len(prev_token)):
# (item may not be a string! only the strings are text.)
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
# Update the current font.
# prev_prev_token holds the font 'name'. The name must be looked up
# in the content stream's resource dictionary, which is page.Resources,
# plus any resource dictionaries above it in the document hierarchy.
current_font = None
resources = page.Resources
while resources and not current_font:
current_font = resources.Font[prev_prev_token]
resources = resources.Parent
# Remember the previously seen token in case the next operator is a text-showing
# operator -- in which case this was the operand. Remember the token before that
# because it may be a font name for the Tf operator.
prev_prev_token = prev_token
prev_token = token
return (text_tokens, page_tokens)
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def chunk_triples(s):
while len(s) >= 3:
yield (s.pop(0), s.pop(0), s.pop(0))
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([cmap])
# print(cmap.stream, file=sys.stderr)
# This is based on https://github.com/euske/pdfminer/blob/master/pdfminer/cmapdb.py.
from pdfrw import PdfString, PdfArray
in_cmap = False
operand_stack = []
codespacerange = []
def code_to_int(code):
# decode hex encoding
code = code.to_bytes()
if sys.version_info < (3,):
code = (ord(c) for c in code)
from functools import reduce
return reduce(lambda x0, x: x0 * 256 + x, (b for b in code))
def add_mapping(code, char, offset=0):
# Is this a mapping for a one-byte or two-byte character code?
width = len(codespacerange[0].to_bytes())
assert len(codespacerange[1].to_bytes()) == width
if width == 1:
# one-byte entry
if sys.version_info < (3,):
code = chr(code)
else:
code = bytes([code])
elif width == 2:
if sys.version_info < (3,):
code = chr(code // 256) + chr(code & 255)
else:
code = bytes([code // 256, code & 255])
else:
raise ValueError("Invalid code space range %s?" % repr(codespacerange))
# Some range operands take an array.
if isinstance(char, PdfArray):
char = char[offset]
# The Unicode character is given usually as a hex string of one or more
# two-byte Unicode code points.
if isinstance(char, PdfString):
char = char.to_bytes()
if sys.version_info < (3,): char = (ord(c) for c in char)
c = ""
for xh, xl in chunk_pairs(list(char)):
c += (chr if sys.version_info >= (3,) else unichr)(xh * 256 + xl)
char = c
if offset > 0:
char = char[0:-1] + (chr if sys.version_info >= (3,) else unichr)(ord(char[-1]) + offset)
else:
assert offset == 0
self.bytes_to_unicode[code] = char
self.unicode_to_bytes[char] = code
for token in tokenize_streams([cmap.stream]):
if token == "begincmap":
in_cmap = True
operand_stack[:] = []
continue
elif token == "endcmap":
in_cmap = False
continue
if not in_cmap:
continue
if token == "def":
name = operand_stack.pop(0)
value = operand_stack.pop(0)
self.defns[name] = value
elif token == "usecmap":
self.usecmap = self.pop(0)
elif token == "begincodespacerange":
operand_stack[:] = []
elif token == "endcodespacerange":
codespacerange = [operand_stack.pop(0), operand_stack.pop(0)]
elif token in ("begincidrange", "beginbfrange"):
operand_stack[:] = []
elif token in ("endcidrange", "endbfrange"):
for (code1, code2, cid_or_name1) in chunk_triples(operand_stack):
if not isinstance(code1, PdfString) or not isinstance(code2, PdfString): continue
code1 = code_to_int(code1)
code2 = code_to_int(code2)
for code in range(code1, code2 + 1):
add_mapping(code, cid_or_name1, code - code1)
operand_stack[:] = []
elif token in ("begincidchar", "beginbfchar"):
operand_stack[:] = []
elif token in ("endcidchar", "endbfchar"):
for (code, char) in chunk_pairs(operand_stack):
if not isinstance(code, PdfString): continue
add_mapping(code_to_int(code), char)
operand_stack[:] = []
elif token == "beginnotdefrange":
operand_stack[:] = []
elif token == "endnotdefrange":
operand_stack[:] = []
else:
operand_stack.append(token)
def dump(self):
for code, char in self.bytes_to_unicode.items():
print(repr(code), char)
def decode(self, string):
ret = []
i = 0;
while i < len(string):
if string[i:i + 1] in self.bytes_to_unicode:
# byte matches a single-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 1]])
i += 1
elif string[i:i + 2] in self.bytes_to_unicode:
# next two bytes matches a multi-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 2]])
i += 2
else:
ret.append("?")
i += 1
return "".join(ret)
def encode(self, string):
ret = []
for c in string:
ret.append(self.unicode_to_bytes.get(c, b""))
return b"".join(ret)
def toUnicode(string, font, fontcache):
# This is hard!
code
if not font:
# There is no font for this text. Assume Latin-1.
return string.decode("Latin-1")
elif font.ToUnicode:
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([font.ToUnicode])
# Use the CMap, which maps character codes to Unicode code points.
if font.ToUnicode.stream not in fontcache:
fontcache[font.ToUnicode.stream] = CMap(font.ToUnicode)
cmap = fontcache[font.ToUnicode.stream]
string = cmap.decode(string)
# print(string, end='', file=sys.stderr)
# sys.stderr.write(string)
return string
elif font.Encoding == "/WinAnsiEncoding":
return string.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string.decode("mac_roman", "replace")
else:
return "?"
# raise ValueError("Don't know how to decode data from font %s." % font)
def fromUnicode(string, font, fontcache, options):
# Filter out characters that are not likely to have renderable glyphs
# because the character didn't occur in the original PDF in its font.
# For any character that didn't occur in the original PDF, replace it
# with the first character in options.content_replacement_glyphs that
# did occur in the original PDF. If none ocurred, delete the character.
if font and font.BaseFont in fontcache:
char_occurs = fontcache[font.BaseFont]
code
def map_char(c):
for cc in [c] + options.content_replacement_glyphs:
if cc in char_occurs:
return cc
return "" # no replacement glyph => omit character
string = "".join(map_char(c) for c in string)
# Encode the Unicode string in the same encoding that it was originally
# stored in --- based on the font that was active when the token was
# used in a text-showing operation.
if not font:
# There was no font for this text. Assume Latin-1.
return string.encode("Latin-1")
elif font.ToUnicode and font.ToUnicode.stream in fontcache:
# Convert the Unicode code points back to one/two-byte CIDs.
cmap = fontcache[font.ToUnicode.stream]
return cmap.encode(string)
# Convert using a simple encoding.
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
# Don't know how to handle this sort of font.
else:
raise ValueError("Don't know how to encode data to font %s." % font)
def update_text_layer(options, text_tokens, page_tokens):
if len(text_tokens) == 0:
# No text content.
return
code
# Apply each regular expression to the text content...
for pattern, function in options.content_filters:
# Finding all matches...
text_tokens_index = 0
text_tokens_charpos = 0
text_tokens_token_xdiff = 0
text_content = "".join(t.value for t in text_tokens)
for m in pattern.finditer(text_content):
# We got a match at text_content[i1:i2].
i1 = m.start()
i2 = m.end()
# Pass the matched text to the replacement function to get replaced text.
replacement = function(m)
# Do a text replacement in the tokens that produced this text content.
# It may have been produced by multiple tokens, so loop until we find them all.
while i1 < i2:
# Find the original tokens in the content stream that
# produced the matched text. Start by advancing over any
# tokens that are entirely before this span of text.
while text_tokens_index < len(text_tokens) and \
text_tokens_charpos + len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff <= i1:
text_tokens_charpos += len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff
text_tokens_index += 1
text_tokens_token_xdiff = 0
if text_tokens_index == len(text_tokens): break
assert (text_tokens_charpos <= i1)
# The token at text_tokens_index, and possibly subsequent ones,
# are responsible for this text. Replace the matched content
# here with replacement content.
tok = text_tokens[text_tokens_index]
# Where does this match begin within the token's text content?
mpos = i1 - text_tokens_charpos
assert mpos >= 0
# How long is the match within this token?
mlen = min(i2 - i1, len(tok.value) - text_tokens_token_xdiff - mpos)
assert mlen >= 0
# How much should we replace here?
if mlen < (i2 - i1):
# There will be more replaced later, so take the same number
# of characters from the replacement text.
r = replacement[:mlen]
replacement = replacement[mlen:]
else:
# This is the last token in which we'll replace text, so put
# all of the remaining replacement content here.
r = replacement
replacement = None # sanity
# Do the replacement.
tok.value = tok.value[:mpos + text_tokens_token_xdiff] + r + tok.value[
mpos + mlen + text_tokens_token_xdiff:]
text_tokens_token_xdiff += len(r) - mlen
# Advance for next iteration.
i1 += mlen
def update_annotations(document, options):
for page in document.pages:
if hasattr(page, 'Annots') and isinstance(page.Annots, list):
for annotation in page.Annots:
update_annotation(annotation, options)
def update_annotation(annotation, options):
import re
from pdfrw.objects import PdfString
code
# Contents holds a plain-text representation of the annotation
# content, such as for accessibility. All annotation types may
# have a Contents. NM holds the "annotation name" which also
# could have redactable text, I suppose. Markup annotations have
# "T" fields that hold a title / text label. Subj holds a
# comment subject. CA, RC, and AC are used in widget annotations.
for string_field in ("Contents", "NM", "T", "Subj", "CA", "RC", "AC"):
if getattr(annotation, string_field):
value = getattr(annotation, string_field).to_unicode()
for pattern, function in options.content_filters:
value = pattern.sub(function, value)
setattr(annotation, string_field, PdfString.from_unicode(value))
# A rich-text stream. Not implemented. Bail so that we don't
# accidentally leak something that should be redacted.
if annotation.RC:
raise ValueError("Annotation rich-text streams (Annot/RC) are not supported.")
# An action, usually used for links.
if annotation.A:
update_annotation_action(annotation, annotation.A, options)
if annotation.PA:
update_annotation_action(annotation, annotation.PA, options)
# If set, another annotation.
if annotation.Popup:
update_annotation(annotation.Popup, options)
TODO? Redaction annotations have some other attributes that might
have text. But since they're intended for redaction... maybe we
should keep them anyway.
def update_annotation_action(annotation, action, options):
from pdfrw.objects import PdfString
code
if action.URI and options.link_filters:
value = action.URI.to_unicode()
for func in options.link_filters:
value = func(value, annotation)
if value is None:
# Remove annotation by supressing the action.
action.URI = None
else:
action.URI = PdfString.from_unicode(value)
if action.Next:
# May be an Action or array of Actions to execute next.
next_action = action.Next
if isinstance(action.Next, dict):
next_action = [action.Next]
for a in next_action:
update_annotation_action(annotation, a, options)
def apply_updated_text(document, text_tokens, page_tokens):
# Create a new content stream for each page by concatenating the
# tokens in the page_tokens lists.
from pdfrw import PdfArray
for i, page in enumerate(document.pages):
if page.Contents is None: continue # nothing was here
code
# Replace the page's content stream with our updated tokens.
# The content stream may have been an array of streams before,
# so replace the whole thing with a single new stream. Unfortunately
# the str on PdfArray and PdfDict doesn't work right.
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, InlineImage):
return "BI " + " ".join(
tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + " ID " + tok.stream + " EI "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + ">> "
return str(tok)
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream) # reset
if name == "main":
redactor(RedactorOptions())
import sys
import io
import re
from datetime import datetime
from pdfrw import PdfDict, PdfReader, PdfWriter, PdfString, PdfArray, PdfObject
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
from pdfminer.cmapdb import CMap, CMapParser, CMapDB
class RedactorOptions:
input_stream = None
output_stream = None
metadata_filters = {}
xmp_filters = []
xmp_serializer = None
content_filters = []
content_replacement_glyphs = ['?', '#', '*', ' ']
link_filters = []
# 缓存每个字体ToUnicode流对应的 (CMap, UnicodeMap)
fontcache = {}
def load_cmap_and_unicodemap_from_stream(stream_data):
cmap = CMap()
parser = CMapParser(cmap, io.BytesIO(stream_data))
parser.run()
cmap_name = cmap.attrs.get('CMapName', 'Identity-H')
try:
unicodemap = CMapDB.get_unicode_map(cmap_name)
except Exception:
from pdfminer.cmapdb import IdentityUnicodeMap
unicodemap = IdentityUnicodeMap()
return cmap, unicodemap
def toUnicode(string_bytes, font, fontcache):
if not font or not getattr(font, 'ToUnicode', None):
# 没有ToUnicode,简单latin1解码
return string_bytes.decode('latin1', errors='ignore')
stream_data = font.ToUnicode.stream
if isinstance(stream_data, str):
stream_data = stream_data.encode('latin1')
if stream_data not in fontcache:
cmap, unicodemap = load_cmap_and_unicodemap_from_stream(stream_data)
fontcache[stream_data] = (cmap, unicodemap)
else:
cmap, unicodemap = fontcache[stream_data]
ret = []
i = 0
while i < len(string_bytes):
for length in reversed(range(1, 5)):
piece = string_bytes[i:i+length]
cids = list(cmap.decode(piece))
if cids:
try:
chars = [unicodemap.get_unichr(cid) for cid in cids]
except Exception:
chars = ['?'] * len(cids)
ret.extend(chars)
i += length
break
else:
ret.append('?')
i += 1
return ''.join(ret)
def fromUnicode(string, font, fontcache, options):
if not font:
return string.encode('latin1')
if getattr(font, 'Encoding', None) == '/WinAnsiEncoding':
return string.encode('cp1252', errors='replace')
if getattr(font, 'Encoding', None) == '/MacRomanEncoding':
return string.encode('mac_roman', errors='replace')
return b'' # 复杂字体不支持逆转码
class InlineImage(PdfDict):
def read_data(self, tokens):
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0], tokens.current[0][0] + 3)
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
if j >= len(tokens.fdata):
break
o = ord(tokens.fdata[j])
if o in (0x0A, 0x0D) or (0x20 <= o <= 0x7E):
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
if token == "<<":
stack.append((PdfDict, []))
continue
elif token == "[":
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
constructor, content = stack.pop(-1)
if constructor == PdfDict:
content = list(chunk_pairs(content))
token = constructor(content)
elif token == "BI":
stack.append((InlineImage, []))
continue
elif token == "ID":
constructor, content = stack[-1]
content = list(chunk_pairs(content))
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
token, _ = stack.pop(-1)
if len(stack) > 0:
stack[-1][1].append(token)
continue
yield token
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def build_text_layer(document, options):
text_tokens = []
class TextToken:
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
from pdfrw.objects import PdfString
if self.value == self.original_value:
return PdfString.from_bytes(self.raw_original_value)
else:
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "":
return
text_tokens.append(token)
page_tokens = []
for page in document.pages:
token_list = []
page_tokens.append(token_list)
if not page.Contents:
continue
prev_token = None
prev_prev_token = None
current_font = None
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
token = TextToken(token.to_bytes(), current_font)
return token
for token in tokenize_streams(content.stream for content in contents):
token = make_mutable_string_token(token)
token_list.append(token)
if isinstance(token, PdfObject):
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
for i in range(len(prev_token)):
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
current_font = None
resources = page.Resources
while resources and not current_font:
if not resources.Font:
break
current_font = resources.Font[prev_prev_token]
resources = getattr(resources, "Parent", None)
prev_prev_token = prev_token
prev_token = token
return text_tokens, page_tokens
# 其余函数:update_text_layer,update_annotations,apply_updated_text 等保持不变
# 直接用你原代码的实现即可
def redactor(options):
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin
if options.output_stream is None:
options.output_stream = sys.stdout
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer
if options.output_stream is None:
options.output_stream = sys.stdout.buffer
document = PdfReader(options.input_stream)
update_metadata(document, options)
update_xmp_metadata(document, options)
if options.content_filters:
text_tokens, page_tokens = build_text_layer(document, options)
update_text_layer(options, text_tokens, page_tokens)
apply_updated_text(document, text_tokens, page_tokens)
update_annotations(document, options)
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
if __name__ == "__main__":
class RedactorOptionsExtended(RedactorOptions):
content_filters = [
(re.compile("敏感词"), lambda m: "***")
]
redactor(RedactorOptionsExtended())
# Input/Output
input_stream = None
output_stream = None
# Metadata filters map names of entries in the PDF Document Information Dictionary
# (e.g. "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
# and "ModDate") to an array of functions to run on the values of those keys.
#
# Each function is given a pdfrw.objects.PdfString containing the current field value,
# or None if the field is not present in the input PDF, as the function's first argument
# and it must return either a string, a datetime.datetime value (CreationDate and ModDate
# should datetime.datetime values), or None to replace the field's value with. Return
# None to clear the field (unless a later function adds a new value).
#
# The functions are run in order. Each function is given the previous function's return
# value. The last function's return value is put into the output PDF.
#
# If a datetime.datetime is returned without timezone info (a "naive" datetime), then
# it must be in UTC. Use pytz.timezone.localize to encode a local time.
#
# Use "DEFAULT" as a key to apply functions to all metadata fields that have no specific
# functions defined, which is useful to remove all unrecognized fields.
#
# Use "ALL" to appy functions to all metadata fields, after any field-specific
# functions or DEFAULT functions are run.
metadata_filters = {}
# The XMP metadata filters are functions that are passed any existing XMP data and
# return new XMP metadata. The functions are called in order and each is passed the
# result of the previous function. The functions are given an xml.etree.Element object,
# or None, as their first argument and must return an object of the same type, or None.
xmp_filters = []
# This function controls how XML returned by xmp_filters is serialized. Replace this
# function with any function that takes an xml.etree.Element object and returns a string
# (a unicode string --- don't serialize to bytes).
xmp_serializer = None
# The content filters are run on the combined content streams of the pages, as well
# as on each annotation's text attributes separately.
#
# Each filter is a tuple of a compiled regular expression and a function to generate
# replacement text, which is given a re.Match object as its sole argument. It must return a string.
#
# Since spaces in PDFs are sometimes not encoded as text but instead as positional
# offsets (like newlines), the regular expression should treat all spaces as optional.
#
# Since pdfrw doesn't support content stream compression, you should use a tool like qpdf
# to decompress the streams before using this tool (see the README).
content_filters = []
# When replacement text isn't likely to have a glyph stored in the PDF's fonts,
# replace the character with these other characters (if they don't have the same
# problem):
content_replacement_glyphs = ['?', '#', '*', ' ']
# The link filters are run on link annotations. Each link filter is a function
# that is passed the link target (a string holding a URI) and a second argujment
# holding the annotation object. The function should return a new URI or None to
# remove the link.
link_filters = []
def redactor(options):
# This is the function that performs redaction.
code
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin # input stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to
from pdfrw import PdfReader, PdfWriter
# Read the PDF.
document = PdfReader(options.input_stream)
# Modify its Document Information Dictionary metadata.
update_metadata(document, options)
# Modify its XMP metadata.
update_xmp_metadata(document, options)
if options.content_filters:
# Build up the complete text stream of the PDF content.
text_layer = build_text_layer(document, options)
# Apply filters to the text stream.
update_text_layer(options, *text_layer)
# Replace page content streams with updated tokens.
apply_updated_text(document, *text_layer)
# Update annotations.
update_annotations(document, options)
# Write the PDF back out.
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
def update_metadata(trailer, options):
# Update the PDF's Document Information Dictionary, which contains keys like
# Title, Author, Subject, Keywords, Creator, Producer, CreationDate, and ModDate
# (the latter two containing Date values, the rest strings).
code
import codecs
from pdfrw.objects import PdfString, PdfName
# Create the metadata dict if it doesn't exist, since the caller may be adding fields.
if not trailer.Info:
trailer.Info = PdfDict()
# Get a list of all metadata fields that exist in the PDF plus any fields
# that there are metadata filters for (since they may insert field values).
keys = set(str(k)[1:] for k in trailer.Info.keys()) \
| set(k for k in options.metadata_filters.keys() if k not in ("DEFAULT", "ALL"))
# Update each metadata field.
for key in keys:
# Get the functions to apply to this field.
functions = options.metadata_filters.get(key)
if functions is None:
# If nothing is defined for this field, use the DEFAULT functions.
functions = options.metadata_filters.get("DEFAULT", [])
# Append the ALL functions.
functions += options.metadata_filters.get("ALL", [])
# Run the functions on any existing values.
value = trailer.Info[PdfName(key)]
for f in functions:
# Before passing to the function, convert from a PdfString to a Python string.
if isinstance(value, PdfString):
# decode from PDF's "(...)" syntax.
value = value.decode()
# Filter the value.
value = f(value)
# Convert Python data type to PdfString.
if isinstance(value, str) or (sys.version_info < (3,) and isinstance(value, unicode)):
# Convert string to a PdfString instance.
value = PdfString.from_unicode(value)
elif isinstance(value, datetime):
# Convert datetime into a PDF "D" string format.
value = value.strftime("%Y%m%d%H%M%S%z")
if len(value) == 19:
# If TZ info was included, add an apostrophe between the hour/minutes offsets.
value = value[:17] + "'" + value[17:]
value = PdfString("(D:%s)" % value)
elif value is None:
# delete the metadata value
pass
else:
raise ValueError("Invalid type of value returned by metadata_filter function. %s was returned by %s." %
(repr(value), f.__name__ or "anonymous function"))
# Replace value.
trailer.Info[PdfName(key)] = value
def update_xmp_metadata(trailer, options):
if trailer.Root.Metadata:
# Safely parse the existing XMP data.
from defusedxml.ElementTree import fromstring
value = fromstring(trailer.Root.Metadata.stream)
else:
# There is no XMP metadata in the document.
value = None
code
# Run each filter.
for f in options.xmp_filters:
value = f(value)
# Set new metadata.
if value is None:
# Clear it.
trailer.Root.Metadata = None
else:
# Serialize the XML and save it into the PDF metadata.
# Get the serializer.
serializer = options.xmp_serializer
if serializer is None:
# Use a default serializer based on xml.etree.ElementTree.tostring.
def serializer(xml_root):
import xml.etree.ElementTree
if hasattr(xml.etree.ElementTree, 'register_namespace'):
# Beginning with Python 3.2 we can define namespace prefixes.
xml.etree.ElementTree.register_namespace("xmp", "adobe:ns:meta/")
xml.etree.ElementTree.register_namespace("pdf13", "http://ns.adobe.com/pdf/1.3/")
xml.etree.ElementTree.register_namespace("xap", "http://ns.adobe.com/xap/1.0/")
xml.etree.ElementTree.register_namespace("dc", "http://purl.org/dc/elements/1.1/")
xml.etree.ElementTree.register_namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
return xml.etree.ElementTree.tostring(xml_root,
encoding='unicode' if sys.version_info >= (3, 0) else None)
# Create a fresh Metadata dictionary and serialize the XML into it.
trailer.Root.Metadata = PdfDict()
trailer.Root.Metadata.Type = "Metadata"
trailer.Root.Metadata.Subtype = "XML"
trailer.Root.Metadata.stream = serializer(value)
class InlineImage(PdfDict):
def read_data(self, tokens):
# "Unless the image uses ASCIIHexDecode or ASCII85Decode as one
# of its filters, the ID operator should be followed by a
# single white-space character, and the next character is
# interpreted as the first byte of image data.
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0],
tokens.current[0][0] + 3)
code
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
# 0: image data or trailing whitespace
# 1: E
# 2: I
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
o = ord(tokens.fdata[j])
if o == 0x0A: # \n
continue
elif o == 0x0D: # \r
continue
elif o >= 0x20 and o <= 0x7E:
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
# pdfrw's tokenizer PdfTokens does lexical analysis only. But we need
# to collapse arrays ([ .. ]) and dictionaries (<< ... >>) into single
# token entries.
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
# Is this a control token?
if token == "<<":
# begins a dictionary
stack.append((PdfDict, []))
continue
elif token == "[":
# begins an array
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
# ends a dictionary or array
constructor, content = stack.pop(-1)
if constructor == PdfDict:
# Turn flat list into key/value pairs.
content = chunk_pairs(content)
token = constructor(content)
elif token == "BI":
# begins an inline image's dictionary half
stack.append((InlineImage, []))
continue
elif token == "ID":
# divides an inline image's dictionary half and data half
constructor, content = stack[-1]
content = chunk_pairs(content)
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
# ends an inline image
token, _ = stack.pop(-1)
code
# If we're inside something, add this token to that thing.
if len(stack) > 0:
stack[-1][1].append(token)
continue
# Yield it.
yield token
def build_text_layer(document, options):
# Within each page's content stream, look for text-showing operators to
# find the text content of the page. Construct a string that contains the
# entire text content of the document AND a mapping from characters in the
# text content to tokens in the content streams. That lets us modify the
# tokens in the content streams when we find text that we want to redact.
#
# The text-showing operators are:
#
# (text) Tj -- show a string of text
# (text) ' -- move to next line and show a string of text
# aw ac (text) " -- show a string of text with word/character spacing parameters
# [ ... ] TJ -- show text strings from the array, which are interleaved with spacing parameters
#
# (These operators appear only within BT ... ET so-called "text objects",
# although we don't make use of it.)
#
# But since we don't understand any of the other content stream operators,
# and in particular we don't know how many operands each (non-text) operator
# takes, we can never be sure whether what we see in the content stream is
# an operator or an operand. If we see a "Tj", maybe it is the operand of
# some other operator?
#
# We'll assume we can get by just fine, however, assuming that whenever we
# see one of these tokens that it's an operator and not an operand.
#
# But TJ remains a little tricky because its operand is an array that preceeds
# it. Arrays are delimited by square brackets and we need to parse that.
#
# We also have to be concerned with the encoding of the text content, which
# depends on the active font. With a simple font, the text is a string whose
# bytes are glyph codes. With a composite font, a CMap maps multi-byte
# character codes to glyphs. In either case, we must map glyphs to unicode
# characters so that we can pattern match against it.
#
# To know the active font, we look for the " Tf" operator.
code
from pdfrw import PdfObject, PdfString, PdfArray
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
text_tokens = []
fontcache = {}
class TextToken: # 将整个类定义移动到模块顶层(如RedactorOptions下方)
value = None
font = None
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
# __str__ is used for serialization
if self.value == self.original_value:
# If unchanged, return the raw original value without decoding/encoding.
return PdfString.from_bytes(self.raw_original_value)
else:
# If the value changed, encode it from Unicode according to the encoding
# of the font that is active at the location of this token.
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
# __repr__ is used for debugging
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "": return
text_tokens.append(token)
# For each page...
page_tokens = []
for page in document.pages:
# For each token in the content stream...
# Remember this page's revised token list.
token_list = []
page_tokens.append(token_list)
if page.Contents is None:
continue
prev_token = None
prev_prev_token = None
current_font = None
# The page may have one content stream or an array of content streams.
# If an array, they are treated as if they are concatenated into a single
# stream (per the spec).
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
# If a compression Filter is applied, attempt to un-apply it. If an unrecognized
# filter is present, an error is raised. uncompress_streams expects an array of
# streams.
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
token = TextToken(token.to_bytes(), current_font)
# Remember all unicode characters seen in this font so we can
# avoid inserting characters that the PDF isn't likely to have
# a glyph for.
if current_font and current_font.BaseFont:
fontcache.setdefault(current_font.BaseFont, set()).update(token.value)
return token
# Iterate through the tokens in the page's content streams.
for token in tokenize_streams(content.stream for content in contents):
# Replace any string token with our own class that hold a mutable
# value, which is how we'll rewrite content.
token = make_mutable_string_token(token)
# Append the token into a new list that holds all tokens.
token_list.append(token)
# If the token is an operator and we're not inside an array...
if isinstance(token, PdfObject):
# And it's one that we recognize, process it.
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
# Simple text operators.
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
# The text array operator.
for i in range(len(prev_token)):
# (item may not be a string! only the strings are text.)
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
# Update the current font.
# prev_prev_token holds the font 'name'. The name must be looked up
# in the content stream's resource dictionary, which is page.Resources,
# plus any resource dictionaries above it in the document hierarchy.
current_font = None
resources = page.Resources
while resources and not current_font:
current_font = resources.Font[prev_prev_token]
resources = resources.Parent
# Remember the previously seen token in case the next operator is a text-showing
# operator -- in which case this was the operand. Remember the token before that
# because it may be a font name for the Tf operator.
prev_prev_token = prev_token
prev_token = token
return (text_tokens, page_tokens)
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def chunk_triples(s):
while len(s) >= 3:
yield (s.pop(0), s.pop(0), s.pop(0))
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([cmap])
# print(cmap.stream, file=sys.stderr)
# This is based on https://github.com/euske/pdfminer/blob/master/pdfminer/cmapdb.py.
from pdfrw import PdfString, PdfArray
in_cmap = False
operand_stack = []
codespacerange = []
def code_to_int(code):
# decode hex encoding
code = code.to_bytes()
if sys.version_info < (3,):
code = (ord(c) for c in code)
from functools import reduce
return reduce(lambda x0, x: x0 * 256 + x, (b for b in code))
def add_mapping(code, char, offset=0):
# Is this a mapping for a one-byte or two-byte character code?
width = len(codespacerange[0].to_bytes())
assert len(codespacerange[1].to_bytes()) == width
if width == 1:
# one-byte entry
if sys.version_info < (3,):
code = chr(code)
else:
code = bytes([code])
elif width == 2:
if sys.version_info < (3,):
code = chr(code // 256) + chr(code & 255)
else:
code = bytes([code // 256, code & 255])
else:
raise ValueError("Invalid code space range %s?" % repr(codespacerange))
# Some range operands take an array.
if isinstance(char, PdfArray):
char = char[offset]
# The Unicode character is given usually as a hex string of one or more
# two-byte Unicode code points.
if isinstance(char, PdfString):
char = char.to_bytes()
if sys.version_info < (3,): char = (ord(c) for c in char)
c = ""
for xh, xl in chunk_pairs(list(char)):
c += (chr if sys.version_info >= (3,) else unichr)(xh * 256 + xl)
char = c
if offset > 0:
char = char[0:-1] + (chr if sys.version_info >= (3,) else unichr)(ord(char[-1]) + offset)
else:
assert offset == 0
self.bytes_to_unicode[code] = char
self.unicode_to_bytes[char] = code
for token in tokenize_streams([cmap.stream]):
if token == "begincmap":
in_cmap = True
operand_stack[:] = []
continue
elif token == "endcmap":
in_cmap = False
continue
if not in_cmap:
continue
if token == "def":
name = operand_stack.pop(0)
value = operand_stack.pop(0)
self.defns[name] = value
elif token == "usecmap":
self.usecmap = self.pop(0)
elif token == "begincodespacerange":
operand_stack[:] = []
elif token == "endcodespacerange":
codespacerange = [operand_stack.pop(0), operand_stack.pop(0)]
elif token in ("begincidrange", "beginbfrange"):
operand_stack[:] = []
elif token in ("endcidrange", "endbfrange"):
for (code1, code2, cid_or_name1) in chunk_triples(operand_stack):
if not isinstance(code1, PdfString) or not isinstance(code2, PdfString): continue
code1 = code_to_int(code1)
code2 = code_to_int(code2)
for code in range(code1, code2 + 1):
add_mapping(code, cid_or_name1, code - code1)
operand_stack[:] = []
elif token in ("begincidchar", "beginbfchar"):
operand_stack[:] = []
elif token in ("endcidchar", "endbfchar"):
for (code, char) in chunk_pairs(operand_stack):
if not isinstance(code, PdfString): continue
add_mapping(code_to_int(code), char)
operand_stack[:] = []
elif token == "beginnotdefrange":
operand_stack[:] = []
elif token == "endnotdefrange":
operand_stack[:] = []
else:
operand_stack.append(token)
def dump(self):
for code, char in self.bytes_to_unicode.items():
print(repr(code), char)
def decode(self, string):
ret = []
i = 0;
while i < len(string):
if string[i:i + 1] in self.bytes_to_unicode:
# byte matches a single-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 1]])
i += 1
elif string[i:i + 2] in self.bytes_to_unicode:
# next two bytes matches a multi-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 2]])
i += 2
else:
ret.append("?")
i += 1
return "".join(ret)
def encode(self, string):
ret = []
for c in string:
ret.append(self.unicode_to_bytes.get(c, b""))
return b"".join(ret)
def toUnicode(string, font, fontcache):
# This is hard!
code
if not font:
# There is no font for this text. Assume Latin-1.
return string.decode("Latin-1")
elif font.ToUnicode:
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([font.ToUnicode])
# Use the CMap, which maps character codes to Unicode code points.
if font.ToUnicode.stream not in fontcache:
fontcache[font.ToUnicode.stream] = CMap(font.ToUnicode)
cmap = fontcache[font.ToUnicode.stream]
string = cmap.decode(string)
# print(string, end='', file=sys.stderr)
# sys.stderr.write(string)
return string
elif font.Encoding == "/WinAnsiEncoding":
return string.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string.decode("mac_roman", "replace")
else:
return "?"
# raise ValueError("Don't know how to decode data from font %s." % font)
def fromUnicode(string, font, fontcache, options):
# Filter out characters that are not likely to have renderable glyphs
# because the character didn't occur in the original PDF in its font.
# For any character that didn't occur in the original PDF, replace it
# with the first character in options.content_replacement_glyphs that
# did occur in the original PDF. If none ocurred, delete the character.
if font and font.BaseFont in fontcache:
char_occurs = fontcache[font.BaseFont]
code
def map_char(c):
for cc in [c] + options.content_replacement_glyphs:
if cc in char_occurs:
return cc
return "" # no replacement glyph => omit character
string = "".join(map_char(c) for c in string)
# Encode the Unicode string in the same encoding that it was originally
# stored in --- based on the font that was active when the token was
# used in a text-showing operation.
if not font:
# There was no font for this text. Assume Latin-1.
return string.encode("Latin-1")
elif font.ToUnicode and font.ToUnicode.stream in fontcache:
# Convert the Unicode code points back to one/two-byte CIDs.
cmap = fontcache[font.ToUnicode.stream]
return cmap.encode(string)
# Convert using a simple encoding.
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
# Don't know how to handle this sort of font.
else:
raise ValueError("Don't know how to encode data to font %s." % font)
def update_text_layer(options, text_tokens, page_tokens):
if len(text_tokens) == 0:
# No text content.
return
code
# Apply each regular expression to the text content...
for pattern, function in options.content_filters:
# Finding all matches...
text_tokens_index = 0
text_tokens_charpos = 0
text_tokens_token_xdiff = 0
text_content = "".join(t.value for t in text_tokens)
for m in pattern.finditer(text_content):
# We got a match at text_content[i1:i2].
i1 = m.start()
i2 = m.end()
# Pass the matched text to the replacement function to get replaced text.
replacement = function(m)
# Do a text replacement in the tokens that produced this text content.
# It may have been produced by multiple tokens, so loop until we find them all.
while i1 < i2:
# Find the original tokens in the content stream that
# produced the matched text. Start by advancing over any
# tokens that are entirely before this span of text.
while text_tokens_index < len(text_tokens) and \
text_tokens_charpos + len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff <= i1:
text_tokens_charpos += len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff
text_tokens_index += 1
text_tokens_token_xdiff = 0
if text_tokens_index == len(text_tokens): break
assert (text_tokens_charpos <= i1)
# The token at text_tokens_index, and possibly subsequent ones,
# are responsible for this text. Replace the matched content
# here with replacement content.
tok = text_tokens[text_tokens_index]
# Where does this match begin within the token's text content?
mpos = i1 - text_tokens_charpos
assert mpos >= 0
# How long is the match within this token?
mlen = min(i2 - i1, len(tok.value) - text_tokens_token_xdiff - mpos)
assert mlen >= 0
# How much should we replace here?
if mlen < (i2 - i1):
# There will be more replaced later, so take the same number
# of characters from the replacement text.
r = replacement[:mlen]
replacement = replacement[mlen:]
else:
# This is the last token in which we'll replace text, so put
# all of the remaining replacement content here.
r = replacement
replacement = None # sanity
# Do the replacement.
tok.value = tok.value[:mpos + text_tokens_token_xdiff] + r + tok.value[
mpos + mlen + text_tokens_token_xdiff:]
text_tokens_token_xdiff += len(r) - mlen
# Advance for next iteration.
i1 += mlen
def update_annotations(document, options):
for page in document.pages:
if hasattr(page, 'Annots') and isinstance(page.Annots, list):
for annotation in page.Annots:
update_annotation(annotation, options)
def update_annotation(annotation, options):
import re
from pdfrw.objects import PdfString
code
# Contents holds a plain-text representation of the annotation
# content, such as for accessibility. All annotation types may
# have a Contents. NM holds the "annotation name" which also
# could have redactable text, I suppose. Markup annotations have
# "T" fields that hold a title / text label. Subj holds a
# comment subject. CA, RC, and AC are used in widget annotations.
for string_field in ("Contents", "NM", "T", "Subj", "CA", "RC", "AC"):
if getattr(annotation, string_field):
value = getattr(annotation, string_field).to_unicode()
for pattern, function in options.content_filters:
value = pattern.sub(function, value)
setattr(annotation, string_field, PdfString.from_unicode(value))
# A rich-text stream. Not implemented. Bail so that we don't
# accidentally leak something that should be redacted.
if annotation.RC:
raise ValueError("Annotation rich-text streams (Annot/RC) are not supported.")
# An action, usually used for links.
if annotation.A:
update_annotation_action(annotation, annotation.A, options)
if annotation.PA:
update_annotation_action(annotation, annotation.PA, options)
# If set, another annotation.
if annotation.Popup:
update_annotation(annotation.Popup, options)
TODO? Redaction annotations have some other attributes that might
have text. But since they're intended for redaction... maybe we
should keep them anyway.
def update_annotation_action(annotation, action, options):
from pdfrw.objects import PdfString
code
if action.URI and options.link_filters:
value = action.URI.to_unicode()
for func in options.link_filters:
value = func(value, annotation)
if value is None:
# Remove annotation by supressing the action.
action.URI = None
else:
action.URI = PdfString.from_unicode(value)
if action.Next:
# May be an Action or array of Actions to execute next.
next_action = action.Next
if isinstance(action.Next, dict):
next_action = [action.Next]
for a in next_action:
update_annotation_action(annotation, a, options)
def apply_updated_text(document, text_tokens, page_tokens):
# Create a new content stream for each page by concatenating the
# tokens in the page_tokens lists.
from pdfrw import PdfArray
for i, page in enumerate(document.pages):
if page.Contents is None: continue # nothing was here
code
# Replace the page's content stream with our updated tokens.
# The content stream may have been an array of streams before,
# so replace the whole thing with a single new stream. Unfortunately
# the str on PdfArray and PdfDict doesn't work right.
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, InlineImage):
return "BI " + " ".join(
tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + " ID " + tok.stream + " EI "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + ">> "
return str(tok)
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream) # reset
if name == "main":
redactor(RedactorOptions())
这是原有代码,请整合pdfplumber 完整示例
import sys
import io
import re
import tempfile
import os
from pdfrw import PdfReader, PdfWriter, PdfString, PdfArray, PdfDict, PdfObject
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
import pdfplumber
class RedactorOptions:
input_stream = None
output_stream = None
metadata_filters = {}
xmp_filters = []
xmp_serializer = None
content_filters = []
content_replacement_glyphs = ['?', '#', '*', ' ']
link_filters = []
def extract_page_texts(pdf_path):
with pdfplumber.open(pdf_path) as pdf:
return [page.extract_text() or '' for page in pdf.pages]
def apply_replacement_to_tokens(page_text, tokens, content_filters):
"""
将pdfplumber匹配的文本替换应用到pdfrw文本token。
这个只是基础示例,适合单token内直接替换。
跨token匹配需要更复杂的逻辑,留待扩展。
"""
text = ''.join(t.value for t in tokens)
offset = 0
token_idx = 0
for pattern, repl_func in content_filters:
for match in pattern.finditer(page_text):
start, end = match.start(), match.end()
repl_text = repl_func(match)
# 找出对应token
while token_idx < len(tokens) and offset + len(tokens[token_idx].value) <= start:
offset += len(tokens[token_idx].value)
token_idx += 1
if token_idx == len(tokens):
break
tok = tokens[token_idx]
local_start = start - offset
local_end = min(len(tok.value), end - offset)
# 仅替换token内匹配的部分,跨token替换可以进一步扩展
tok.value = tok.value[:local_start] + repl_text + tok.value[local_end:]
def build_text_layer(document, options):
"""
基本保持你原来的build_text_layer,用于获取token列表,为替换做准备
"""
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects import PdfString, PdfArray, PdfObject
text_tokens = []
class TextToken:
def __init__(self, value, font):
self.font = font
self.raw_original_value = value
self.original_value = value.decode('latin1', errors='ignore') # 可换成正确toUnicode版本
self.value = self.original_value
def __str__(self):
from pdfrw.objects import PdfString
if self.value == self.original_value:
return PdfString.from_bytes(self.raw_original_value)
else:
return PdfString.from_unicode(self.value)
def __repr__(self):
return f'Token<{self.value}>'
page_tokens = []
for page in document.pages:
token_list = []
page_tokens.append(token_list)
if not page.Contents:
continue
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
uncompress_streams(contents)
for content in contents:
if isinstance(content, PdfString):
token = TextToken(content.to_bytes(), None)
token_list.append(token)
text_tokens.append(token)
else:
# 如果需要更复杂token结构解码,请用你原来的 tokenize_streams
pass
return text_tokens, page_tokens
def update_text_layer(options, text_tokens, page_tokens, page_texts):
"""
使用pdfplumber的文本做匹配,并修改token内容
"""
for i, tokens in enumerate(page_tokens):
if i >= len(page_texts):
break
page_text = page_texts[i]
apply_replacement_to_tokens(page_text, tokens, options.content_filters)
def apply_updated_text(document, text_tokens, page_tokens):
"""
将修改后的token序列写回页面流
"""
from pdfrw import PdfArray, PdfDict
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(k) + " " + tok_str(v) for k, v in tok.items()) + ">> "
return str(tok)
for i, page in enumerate(document.pages):
if page.Contents is None:
continue
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream)
def redactor(options):
import tempfile
# 临时把流写文件,供pdfplumber使用
if hasattr(options.input_stream, "name"):
pdf_path = options.input_stream.name
else:
tmpf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
tmpf.write(options.input_stream.read())
tmpf.close()
pdf_path = tmpf.name
options.input_stream = open(pdf_path, "rb") # 重新打开流
page_texts = extract_page_texts(pdf_path)
document = PdfReader(options.input_stream)
update_metadata(document, options)
update_xmp_metadata(document, options)
if options.content_filters:
text_tokens, page_tokens = build_text_layer(document, options)
update_text_layer(options, text_tokens, page_tokens, page_texts)
apply_updated_text(document, text_tokens, page_tokens)
update_annotations(document, options)
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
# 删除临时PDF
if tmpf:
os.unlink(tmpf.name)
if __name__ == "__main__":
import re
class ExtendedOptions(RedactorOptions):
content_filters = [(re.compile(r"敏感词"), lambda m: "***")]
options = ExtendedOptions()
if len(sys.argv) == 3:
with open(sys.argv[1], "rb") as fin:
options.input_stream = io.BytesIO(fin.read())
options.output_stream = open(sys.argv[2], "wb")
else:
options.input_stream = sys.stdin.buffer
options.output_stream = sys.stdout.buffer
redactor(options)
# Input/Output
input_stream = None
output_stream = None
# Metadata filters map names of entries in the PDF Document Information Dictionary
# (e.g. "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
# and "ModDate") to an array of functions to run on the values of those keys.
#
# Each function is given a pdfrw.objects.PdfString containing the current field value,
# or None if the field is not present in the input PDF, as the function's first argument
# and it must return either a string, a datetime.datetime value (CreationDate and ModDate
# should datetime.datetime values), or None to replace the field's value with. Return
# None to clear the field (unless a later function adds a new value).
#
# The functions are run in order. Each function is given the previous function's return
# value. The last function's return value is put into the output PDF.
#
# If a datetime.datetime is returned without timezone info (a "naive" datetime), then
# it must be in UTC. Use pytz.timezone.localize to encode a local time.
#
# Use "DEFAULT" as a key to apply functions to all metadata fields that have no specific
# functions defined, which is useful to remove all unrecognized fields.
#
# Use "ALL" to appy functions to all metadata fields, after any field-specific
# functions or DEFAULT functions are run.
metadata_filters = {}
# The XMP metadata filters are functions that are passed any existing XMP data and
# return new XMP metadata. The functions are called in order and each is passed the
# result of the previous function. The functions are given an xml.etree.Element object,
# or None, as their first argument and must return an object of the same type, or None.
xmp_filters = []
# This function controls how XML returned by xmp_filters is serialized. Replace this
# function with any function that takes an xml.etree.Element object and returns a string
# (a unicode string --- don't serialize to bytes).
xmp_serializer = None
# The content filters are run on the combined content streams of the pages, as well
# as on each annotation's text attributes separately.
#
# Each filter is a tuple of a compiled regular expression and a function to generate
# replacement text, which is given a re.Match object as its sole argument. It must return a string.
#
# Since spaces in PDFs are sometimes not encoded as text but instead as positional
# offsets (like newlines), the regular expression should treat all spaces as optional.
#
# Since pdfrw doesn't support content stream compression, you should use a tool like qpdf
# to decompress the streams before using this tool (see the README).
content_filters = []
# When replacement text isn't likely to have a glyph stored in the PDF's fonts,
# replace the character with these other characters (if they don't have the same
# problem):
content_replacement_glyphs = ['?', '#', '*', ' ']
# The link filters are run on link annotations. Each link filter is a function
# that is passed the link target (a string holding a URI) and a second argujment
# holding the annotation object. The function should return a new URI or None to
# remove the link.
link_filters = []
def redactor(options):
# This is the function that performs redaction.
code
if sys.version_info < (3,):
if options.input_stream is None:
options.input_stream = sys.stdin # input stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
else:
if options.input_stream is None:
options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
if options.output_stream is None:
options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to
from pdfrw import PdfReader, PdfWriter
# Read the PDF.
document = PdfReader(options.input_stream)
# Modify its Document Information Dictionary metadata.
update_metadata(document, options)
# Modify its XMP metadata.
update_xmp_metadata(document, options)
if options.content_filters:
# Build up the complete text stream of the PDF content.
text_layer = build_text_layer(document, options)
# Apply filters to the text stream.
update_text_layer(options, *text_layer)
# Replace page content streams with updated tokens.
apply_updated_text(document, *text_layer)
# Update annotations.
update_annotations(document, options)
# Write the PDF back out.
writer = PdfWriter()
writer.trailer = document
writer.write(options.output_stream)
def update_metadata(trailer, options):
# Update the PDF's Document Information Dictionary, which contains keys like
# Title, Author, Subject, Keywords, Creator, Producer, CreationDate, and ModDate
# (the latter two containing Date values, the rest strings).
code
import codecs
from pdfrw.objects import PdfString, PdfName
# Create the metadata dict if it doesn't exist, since the caller may be adding fields.
if not trailer.Info:
trailer.Info = PdfDict()
# Get a list of all metadata fields that exist in the PDF plus any fields
# that there are metadata filters for (since they may insert field values).
keys = set(str(k)[1:] for k in trailer.Info.keys()) \
| set(k for k in options.metadata_filters.keys() if k not in ("DEFAULT", "ALL"))
# Update each metadata field.
for key in keys:
# Get the functions to apply to this field.
functions = options.metadata_filters.get(key)
if functions is None:
# If nothing is defined for this field, use the DEFAULT functions.
functions = options.metadata_filters.get("DEFAULT", [])
# Append the ALL functions.
functions += options.metadata_filters.get("ALL", [])
# Run the functions on any existing values.
value = trailer.Info[PdfName(key)]
for f in functions:
# Before passing to the function, convert from a PdfString to a Python string.
if isinstance(value, PdfString):
# decode from PDF's "(...)" syntax.
value = value.decode()
# Filter the value.
value = f(value)
# Convert Python data type to PdfString.
if isinstance(value, str) or (sys.version_info < (3,) and isinstance(value, unicode)):
# Convert string to a PdfString instance.
value = PdfString.from_unicode(value)
elif isinstance(value, datetime):
# Convert datetime into a PDF "D" string format.
value = value.strftime("%Y%m%d%H%M%S%z")
if len(value) == 19:
# If TZ info was included, add an apostrophe between the hour/minutes offsets.
value = value[:17] + "'" + value[17:]
value = PdfString("(D:%s)" % value)
elif value is None:
# delete the metadata value
pass
else:
raise ValueError("Invalid type of value returned by metadata_filter function. %s was returned by %s." %
(repr(value), f.__name__ or "anonymous function"))
# Replace value.
trailer.Info[PdfName(key)] = value
def update_xmp_metadata(trailer, options):
if trailer.Root.Metadata:
# Safely parse the existing XMP data.
from defusedxml.ElementTree import fromstring
value = fromstring(trailer.Root.Metadata.stream)
else:
# There is no XMP metadata in the document.
value = None
code
# Run each filter.
for f in options.xmp_filters:
value = f(value)
# Set new metadata.
if value is None:
# Clear it.
trailer.Root.Metadata = None
else:
# Serialize the XML and save it into the PDF metadata.
# Get the serializer.
serializer = options.xmp_serializer
if serializer is None:
# Use a default serializer based on xml.etree.ElementTree.tostring.
def serializer(xml_root):
import xml.etree.ElementTree
if hasattr(xml.etree.ElementTree, 'register_namespace'):
# Beginning with Python 3.2 we can define namespace prefixes.
xml.etree.ElementTree.register_namespace("xmp", "adobe:ns:meta/")
xml.etree.ElementTree.register_namespace("pdf13", "http://ns.adobe.com/pdf/1.3/")
xml.etree.ElementTree.register_namespace("xap", "http://ns.adobe.com/xap/1.0/")
xml.etree.ElementTree.register_namespace("dc", "http://purl.org/dc/elements/1.1/")
xml.etree.ElementTree.register_namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
return xml.etree.ElementTree.tostring(xml_root,
encoding='unicode' if sys.version_info >= (3, 0) else None)
# Create a fresh Metadata dictionary and serialize the XML into it.
trailer.Root.Metadata = PdfDict()
trailer.Root.Metadata.Type = "Metadata"
trailer.Root.Metadata.Subtype = "XML"
trailer.Root.Metadata.stream = serializer(value)
class InlineImage(PdfDict):
def read_data(self, tokens):
# "Unless the image uses ASCIIHexDecode or ASCII85Decode as one
# of its filters, the ID operator should be followed by a
# single white-space character, and the next character is
# interpreted as the first byte of image data.
if tokens.current[0][1] > tokens.current[0][0] + 3:
tokens.current[0] = (tokens.current[0][0],
tokens.current[0][0] + 3)
code
start = tokens.floc
state = 0
whitespace = (" ", "\n", "\r")
# 0: image data or trailing whitespace
# 1: E
# 2: I
for i in range(start, len(tokens.fdata)):
if state == 0:
if tokens.fdata[i] == "E":
state = 1
elif state == 1:
if tokens.fdata[i] == "I":
state = 2
else:
state = 0
elif state == 2:
if tokens.fdata[i] in whitespace:
for j in range(i + 1, i + 6):
o = ord(tokens.fdata[j])
if o == 0x0A: # \n
continue
elif o == 0x0D: # \r
continue
elif o >= 0x20 and o <= 0x7E:
continue
else:
state = 0
break
else:
end = i - 3
assert tokens.fdata[end] in whitespace
break
else:
state = 0
self._stream = tokens.fdata[start:end]
tokens.floc = end
def tokenize_streams(streams):
# pdfrw's tokenizer PdfTokens does lexical analysis only. But we need
# to collapse arrays ([ .. ]) and dictionaries (<< ... >>) into single
# token entries.
from pdfrw import PdfTokens, PdfArray
stack = []
for stream in streams:
tokens = PdfTokens(stream)
for token in tokens:
# Is this a control token?
if token == "<<":
# begins a dictionary
stack.append((PdfDict, []))
continue
elif token == "[":
# begins an array
stack.append((PdfArray, []))
continue
elif token in (">>", "]"):
# ends a dictionary or array
constructor, content = stack.pop(-1)
if constructor == PdfDict:
# Turn flat list into key/value pairs.
content = chunk_pairs(content)
token = constructor(content)
elif token == "BI":
# begins an inline image's dictionary half
stack.append((InlineImage, []))
continue
elif token == "ID":
# divides an inline image's dictionary half and data half
constructor, content = stack[-1]
content = chunk_pairs(content)
img = constructor(content)
img.read_data(tokens)
stack[-1] = (img, None)
continue
elif token == "EI":
# ends an inline image
token, _ = stack.pop(-1)
code
# If we're inside something, add this token to that thing.
if len(stack) > 0:
stack[-1][1].append(token)
continue
# Yield it.
yield token
def build_text_layer(document, options):
# Within each page's content stream, look for text-showing operators to
# find the text content of the page. Construct a string that contains the
# entire text content of the document AND a mapping from characters in the
# text content to tokens in the content streams. That lets us modify the
# tokens in the content streams when we find text that we want to redact.
#
# The text-showing operators are:
#
# (text) Tj -- show a string of text
# (text) ' -- move to next line and show a string of text
# aw ac (text) " -- show a string of text with word/character spacing parameters
# [ ... ] TJ -- show text strings from the array, which are interleaved with spacing parameters
#
# (These operators appear only within BT ... ET so-called "text objects",
# although we don't make use of it.)
#
# But since we don't understand any of the other content stream operators,
# and in particular we don't know how many operands each (non-text) operator
# takes, we can never be sure whether what we see in the content stream is
# an operator or an operand. If we see a "Tj", maybe it is the operand of
# some other operator?
#
# We'll assume we can get by just fine, however, assuming that whenever we
# see one of these tokens that it's an operator and not an operand.
#
# But TJ remains a little tricky because its operand is an array that preceeds
# it. Arrays are delimited by square brackets and we need to parse that.
#
# We also have to be concerned with the encoding of the text content, which
# depends on the active font. With a simple font, the text is a string whose
# bytes are glyph codes. With a composite font, a CMap maps multi-byte
# character codes to glyphs. In either case, we must map glyphs to unicode
# characters so that we can pattern match against it.
#
# To know the active font, we look for the " Tf" operator.
code
from pdfrw import PdfObject, PdfString, PdfArray
from pdfrw.uncompress import uncompress as uncompress_streams
from pdfrw.objects.pdfname import BasePdfName
text_tokens = []
fontcache = {}
class TextToken: # 将整个类定义移动到模块顶层(如RedactorOptions下方)
value = None
font = None
def __init__(self,PdfString_Obj, value, font):
self.font = font
self.token = PdfString_Obj #修改bug,个别汉字PdfString.from_bytes后就变了不显示,现在改为直接缓存PdfString_Obj,之后也返回PdfString_Obj
self.raw_original_value = value
self.original_value = toUnicode(value, font, fontcache)
self.value = self.original_value
def __str__(self):
# __str__ is used for serialization
if self.value == self.original_value:
# If unchanged, return the raw original value without decoding/encoding.
# return PdfString.from_bytes(self.raw_original_value)
return self.token #修改bug,个别汉字PdfString.from_bytes后就变了不显示,现在改为直接缓存PdfString_Obj,之后也返回PdfString_Obj
else:
# If the value changed, encode it from Unicode according to the encoding
# of the font that is active at the location of this token.
return PdfString.from_bytes(fromUnicode(self.value, self.font, fontcache, options))
def __repr__(self):
# __repr__ is used for debugging
return "Token<%s>" % repr(self.value)
def process_text(token):
if token.value == "": return
text_tokens.append(token)
# For each page...
page_tokens = []
for page in document.pages:
# For each token in the content stream...
# Remember this page's revised token list.
token_list = []
page_tokens.append(token_list)
if page.Contents is None:
continue
prev_token = None
prev_prev_token = None
current_font = None
# The page may have one content stream or an array of content streams.
# If an array, they are treated as if they are concatenated into a single
# stream (per the spec).
if isinstance(page.Contents, PdfArray):
contents = list(page.Contents)
else:
contents = [page.Contents]
# If a compression Filter is applied, attempt to un-apply it. If an unrecognized
# filter is present, an error is raised. uncompress_streams expects an array of
# streams.
uncompress_streams(contents)
def make_mutable_string_token(token):
if isinstance(token, PdfString):
txt_token = TextToken(token,token.to_bytes(), current_font)
# Remember all unicode characters seen in this font so we can
# avoid inserting characters that the PDF isn't likely to have
# a glyph for.
if current_font and current_font.BaseFont:
fontcache.setdefault(current_font.BaseFont, set()).update(txt_token.value)
return txt_token
return token
# Iterate through the tokens in the page's content streams.
for token in tokenize_streams(content.stream for content in contents):
# Replace any string token with our own class that hold a mutable
# value, which is how we'll rewrite content.
token = make_mutable_string_token(token)
# Append the token into a new list that holds all tokens.
token_list.append(token)
# If the token is an operator and we're not inside an array...
if isinstance(token, PdfObject):
# And it's one that we recognize, process it.
if token in ("Tj", "'", '"') and isinstance(prev_token, TextToken):
# Simple text operators.
process_text(prev_token)
elif token == "TJ" and isinstance(prev_token, PdfArray):
# The text array operator.
for i in range(len(prev_token)):
# (item may not be a string! only the strings are text.)
prev_token[i] = make_mutable_string_token(prev_token[i])
if isinstance(prev_token[i], TextToken):
process_text(prev_token[i])
elif token == "Tf" and isinstance(prev_prev_token, BasePdfName):
# Update the current font.
# prev_prev_token holds the font 'name'. The name must be looked up
# in the content stream's resource dictionary, which is page.Resources,
# plus any resource dictionaries above it in the document hierarchy.
current_font = None
resources = page.Resources
while resources and not current_font:
current_font = resources.Font[prev_prev_token]
resources = resources.Parent
# Remember the previously seen token in case the next operator is a text-showing
# operator -- in which case this was the operand. Remember the token before that
# because it may be a font name for the Tf operator.
prev_prev_token = prev_token
prev_token = token
return (text_tokens, page_tokens)
def chunk_pairs(s):
while len(s) >= 2:
yield (s.pop(0), s.pop(0))
def chunk_triples(s):
while len(s) >= 3:
yield (s.pop(0), s.pop(0), s.pop(0))
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([cmap])
# print(cmap.stream, file=sys.stderr)
# This is based on https://github.com/euske/pdfminer/blob/master/pdfminer/cmapdb.py.
from pdfrw import PdfString, PdfArray
in_cmap = False
operand_stack = []
codespacerange = []
def code_to_int(code):
# decode hex encoding
code = code.to_bytes()
if sys.version_info < (3,):
code = (ord(c) for c in code)
from functools import reduce
return reduce(lambda x0, x: x0 * 256 + x, (b for b in code))
def add_mapping(code, char, offset=0):
# Is this a mapping for a one-byte or two-byte character code?
width = len(codespacerange[0].to_bytes())
assert len(codespacerange[1].to_bytes()) == width
if width == 1:
# one-byte entry
if sys.version_info < (3,):
code = chr(code)
else:
code = bytes([code])
elif width == 2:
if sys.version_info < (3,):
code = chr(code // 256) + chr(code & 255)
else:
code = bytes([code // 256, code & 255])
else:
raise ValueError("Invalid code space range %s?" % repr(codespacerange))
# Some range operands take an array.
if isinstance(char, PdfArray):
char = char[offset]
# The Unicode character is given usually as a hex string of one or more
# two-byte Unicode code points.
if isinstance(char, PdfString):
char = char.to_bytes()
if sys.version_info < (3,): char = (ord(c) for c in char)
c = ""
for xh, xl in chunk_pairs(list(char)):
c += (chr if sys.version_info >= (3,) else unichr)(xh * 256 + xl)
char = c
if offset > 0:
char = char[0:-1] + (chr if sys.version_info >= (3,) else unichr)(ord(char[-1]) + offset)
else:
assert offset == 0
self.bytes_to_unicode[code] = char
self.unicode_to_bytes[char] = code
for token in tokenize_streams([cmap.stream]):
if token == "begincmap":
in_cmap = True
operand_stack[:] = []
continue
elif token == "endcmap":
in_cmap = False
continue
if not in_cmap:
continue
if token == "def":
name = operand_stack.pop(0)
value = operand_stack.pop(0)
self.defns[name] = value
elif token == "usecmap":
self.usecmap = self.pop(0)
elif token == "begincodespacerange":
operand_stack[:] = []
elif token == "endcodespacerange":
codespacerange = [operand_stack.pop(0), operand_stack.pop(0)]
elif token in ("begincidrange", "beginbfrange"):
operand_stack[:] = []
elif token in ("endcidrange", "endbfrange"):
for (code1, code2, cid_or_name1) in chunk_triples(operand_stack):
if not isinstance(code1, PdfString) or not isinstance(code2, PdfString): continue
code1 = code_to_int(code1)
code2 = code_to_int(code2)
for code in range(code1, code2 + 1):
add_mapping(code, cid_or_name1, code - code1)
operand_stack[:] = []
elif token in ("begincidchar", "beginbfchar"):
operand_stack[:] = []
elif token in ("endcidchar", "endbfchar"):
for (code, char) in chunk_pairs(operand_stack):
if not isinstance(code, PdfString): continue
add_mapping(code_to_int(code), char)
operand_stack[:] = []
elif token == "beginnotdefrange":
operand_stack[:] = []
elif token == "endnotdefrange":
operand_stack[:] = []
else:
operand_stack.append(token)
def dump(self):
for code, char in self.bytes_to_unicode.items():
print(repr(code), char)
def decode(self, string):
ret = []
i = 0;
while i < len(string):
if string[i:i + 1] in self.bytes_to_unicode:
# byte matches a single-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 1]])
i += 1
elif string[i:i + 2] in self.bytes_to_unicode:
# next two bytes matches a multi-byte entry
ret.append(self.bytes_to_unicode[string[i:i + 2]])
i += 2
else:
ret.append("?")
i += 1
return "".join(ret)
def encode(self, string):
ret = []
for c in string:
ret.append(self.unicode_to_bytes.get(c, b""))
return b"".join(ret)
def toUnicode(string, font, fontcache):
# This is hard!
code
if not font:
# There is no font for this text. Assume Latin-1.
return string.decode("Latin-1")
elif font.ToUnicode:
# Decompress the CMap stream & check that it's not compressed in a way
# we can't understand.
from pdfrw.uncompress import uncompress as uncompress_streams
uncompress_streams([font.ToUnicode])
# Use the CMap, which maps character codes to Unicode code points.
if font.ToUnicode.stream not in fontcache:
fontcache[font.ToUnicode.stream] = CMap(font.ToUnicode)
cmap = fontcache[font.ToUnicode.stream]
string = cmap.decode(string)
# print(string, end='', file=sys.stderr)
# sys.stderr.write(string)
return string
elif font.Encoding == "/WinAnsiEncoding":
return string.decode("cp1252", "replace")
elif font.Encoding == "/MacRomanEncoding":
return string.decode("mac_roman", "replace")
else:
return "?"
# raise ValueError("Don't know how to decode data from font %s." % font)
def fromUnicode(string, font, fontcache, options):
# Filter out characters that are not likely to have renderable glyphs
# because the character didn't occur in the original PDF in its font.
# For any character that didn't occur in the original PDF, replace it
# with the first character in options.content_replacement_glyphs that
# did occur in the original PDF. If none ocurred, delete the character.
if font and font.BaseFont in fontcache:
char_occurs = fontcache[font.BaseFont]
code
def map_char(c):
for cc in [c] + options.content_replacement_glyphs:
if cc in char_occurs:
return cc
return "" # no replacement glyph => omit character
string = "".join(map_char(c) for c in string)
# Encode the Unicode string in the same encoding that it was originally
# stored in --- based on the font that was active when the token was
# used in a text-showing operation.
if not font:
# There was no font for this text. Assume Latin-1.
return string.encode("Latin-1")
elif font.ToUnicode and font.ToUnicode.stream in fontcache:
# Convert the Unicode code points back to one/two-byte CIDs.
cmap = fontcache[font.ToUnicode.stream]
return cmap.encode(string)
# Convert using a simple encoding.
elif font.Encoding == "/WinAnsiEncoding":
return string.encode("cp1252")
elif font.Encoding == "/MacRomanEncoding":
return string.encode("mac_roman")
# Don't know how to handle this sort of font.
else:
raise ValueError("Don't know how to encode data to font %s." % font)
def update_text_layer(options, text_tokens, page_tokens):
if len(text_tokens) == 0:
# No text content.
return
code
# Apply each regular expression to the text content...
for pattern, function in options.content_filters:
# Finding all matches...
text_tokens_index = 0
text_tokens_charpos = 0
text_tokens_token_xdiff = 0
text_content = "".join(t.value for t in text_tokens)
for m in pattern.finditer(text_content):
# We got a match at text_content[i1:i2].
i1 = m.start()
i2 = m.end()
# Pass the matched text to the replacement function to get replaced text.
replacement = function(m)
# Do a text replacement in the tokens that produced this text content.
# It may have been produced by multiple tokens, so loop until we find them all.
while i1 < i2:
# Find the original tokens in the content stream that
# produced the matched text. Start by advancing over any
# tokens that are entirely before this span of text.
while text_tokens_index < len(text_tokens) and \
text_tokens_charpos + len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff <= i1:
text_tokens_charpos += len(text_tokens[text_tokens_index].value) - text_tokens_token_xdiff
text_tokens_index += 1
text_tokens_token_xdiff = 0
if text_tokens_index == len(text_tokens): break
assert (text_tokens_charpos <= i1)
# The token at text_tokens_index, and possibly subsequent ones,
# are responsible for this text. Replace the matched content
# here with replacement content.
tok = text_tokens[text_tokens_index]
# Where does this match begin within the token's text content?
mpos = i1 - text_tokens_charpos
assert mpos >= 0
# How long is the match within this token?
mlen = min(i2 - i1, len(tok.value) - text_tokens_token_xdiff - mpos)
assert mlen >= 0
# How much should we replace here?
if mlen < (i2 - i1):
# There will be more replaced later, so take the same number
# of characters from the replacement text.
r = replacement[:mlen]
replacement = replacement[mlen:]
else:
# This is the last token in which we'll replace text, so put
# all of the remaining replacement content here.
r = replacement
replacement = None # sanity
# Do the replacement.
tok.value = tok.value[:mpos + text_tokens_token_xdiff] + r + tok.value[
mpos + mlen + text_tokens_token_xdiff:]
text_tokens_token_xdiff += len(r) - mlen
# Advance for next iteration.
i1 += mlen
def update_annotations(document, options):
for page in document.pages:
if hasattr(page, 'Annots') and isinstance(page.Annots, list):
for annotation in page.Annots:
update_annotation(annotation, options)
def update_annotation(annotation, options):
import re
from pdfrw.objects import PdfString
code
# Contents holds a plain-text representation of the annotation
# content, such as for accessibility. All annotation types may
# have a Contents. NM holds the "annotation name" which also
# could have redactable text, I suppose. Markup annotations have
# "T" fields that hold a title / text label. Subj holds a
# comment subject. CA, RC, and AC are used in widget annotations.
for string_field in ("Contents", "NM", "T", "Subj", "CA", "RC", "AC"):
if getattr(annotation, string_field):
value = getattr(annotation, string_field).to_unicode()
for pattern, function in options.content_filters:
value = pattern.sub(function, value)
setattr(annotation, string_field, PdfString.from_unicode(value))
# A rich-text stream. Not implemented. Bail so that we don't
# accidentally leak something that should be redacted.
if annotation.RC:
raise ValueError("Annotation rich-text streams (Annot/RC) are not supported.")
# An action, usually used for links.
if annotation.A:
update_annotation_action(annotation, annotation.A, options)
if annotation.PA:
update_annotation_action(annotation, annotation.PA, options)
# If set, another annotation.
if annotation.Popup:
update_annotation(annotation.Popup, options)
TODO? Redaction annotations have some other attributes that might
have text. But since they're intended for redaction... maybe we
should keep them anyway.
def update_annotation_action(annotation, action, options):
from pdfrw.objects import PdfString
code
if action.URI and options.link_filters:
value = action.URI.to_unicode()
for func in options.link_filters:
value = func(value, annotation)
if value is None:
# Remove annotation by supressing the action.
action.URI = None
else:
action.URI = PdfString.from_unicode(value)
if action.Next:
# May be an Action or array of Actions to execute next.
next_action = action.Next
if isinstance(action.Next, dict):
next_action = [action.Next]
for a in next_action:
update_annotation_action(annotation, a, options)
def apply_updated_text(document, text_tokens, page_tokens):
# Create a new content stream for each page by concatenating the
# tokens in the page_tokens lists.
from pdfrw import PdfArray,PdfName
for i, page in enumerate(document.pages):
if page.Contents is None: continue # nothing was here
# 保留原始字体资源引用
if hasattr(page, 'Resources') and hasattr(page.Resources, 'Font'):
original_fonts = page.Resources.Font
else:
original_fonts = {}
code
# Replace the page's content stream with our updated tokens.
# The content stream may have been an array of streams before,
# so replace the whole thing with a single new stream. Unfortunately
# the str on PdfArray and PdfDict doesn't work right.
def tok_str(tok):
if isinstance(tok, PdfArray):
return "[ " + " ".join(tok_str(x) for x in tok) + "] "
if isinstance(tok, InlineImage):
return "BI " + " ".join(
tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + " ID " + tok.stream + " EI "
if isinstance(tok, PdfDict):
return "<< " + " ".join(tok_str(x) + " " + tok_str(y) for x, y in tok.items()) + ">> "
else:
return str(tok)
return str(tok)
# 恢复原始字体资源
if hasattr(page, 'Resources'):
page.Resources.Font = original_fonts
page.Contents = PdfDict()
page.Contents.stream = "\n".join(tok_str(tok) for tok in page_tokens[i])
page.Contents.Length = len(page.Contents.stream) # reset