1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| from PyPDF2 import PdfReader import PyPDF2 from pprint import pprint
def walk(obj, fnt, emb): ''' If there is a key called 'BaseFont', that is a font that is used in the document. If there is a key called 'FontName' and another key in the same dictionary object that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is embedded.
We create and add to two sets, fnt = fonts used and emb = fonts embedded. ''' if not hasattr(obj, 'keys'): return None, None fontkeys = set(['/FontFile', '/FontFile2', '/FontFile3']) if '/BaseFont' in obj: fnt.add(obj['/BaseFont']) if '/FontName' in obj: if [x for x in fontkeys if x in obj]: emb.add(obj['/FontName'])
for k in obj.keys(): walk(obj[k], fnt, emb)
return fnt, emb
if __name__ == '__main__': fname = 'liuyao.pdf' pdf = PdfReader(fname) fonts = set() embedded = set() for page in pdf.pages: obj = page.get_object() if type(obj) == PyPDF2.generic.ArrayObject: for i in obj: if hasattr(i, 'keys'): f, e = walk(i, fonts, embedded_fonts) fonts = fonts.union(f) embedded = embedded.union(e) else: f, e = walk(obj['/Resources'], fonts, embedded) fonts = fonts.union(f) embedded = embedded.union(e)
unembedded = fonts - embedded print('Font List') pprint(sorted(list(fonts))) if unembedded: print('\nUnembedded Fonts') pprint(unembedded)
|