使用PyPDF2检测由Google文档生成的PDF文件中的非嵌入式字体

问题描述 投票:1回答:1

我希望有人可以帮助我编写Python函数来检测文件中未嵌入文件的任何字体。我试图使用链接为here的脚本,它可以检测文档字体,但是不能检测嵌入的字体。为了方便起见,我粘贴了以下脚本:

from PyPDF2 import PdfFileReader
import sys

fontkeys = set(['/FontFile', '/FontFile2', '/FontFile3'])

def walk(obj, fnt, emb):
    if '/BaseFont' in obj:
        fnt.add(obj['/BaseFont'])

    elif '/FontName' in obj and fontkeys.intersection(set(obj)):
        emb.add(obj['/FontName'])

    for k in obj:
        if hasattr(obj[k], 'keys'):
            walk(obj[k], fnt, emb)

    return fnt, emb

if __name__ == '__main__':
    fname = sys.argv[1]
    pdf = PdfFileReader(fname)
    fonts = set()
    embedded = set()

    for page in pdf.pages:
        obj = page.getObject()
        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)

例如,我从Google Docs下载了具有Arial字体的PDF(键入一些内容,另存为PDF),并且Adobe Reader已确认该字体已嵌入。但是,脚本返回['/ ArialMT']作为字体,并为嵌入式字体返回一个空集。此外,看起来任何递归对象都不具有键{'/FontFile', '/FontFile2', '/FontFile3'}。我已经在其他PDF上进行了尝试,并且可以正常使用,因此对于Google Docs PDF一定很奇怪。让我知道我可以为该PDF文件提供哪些其他调试信息。

Adobe confirming that the font is embedded

我想到的一件事是,谷歌文档可能只嵌入了14种标准PDF字体中没有的字体。但是,我尝试使用一种奇怪的字体(pacifico)进行了测试,脚本还指出该字体未嵌入,而Adobe声称是这种字体。Pacifico being embedded, script saying its not

我用this PDF进行了尝试,脚本正确地指出已嵌入这14种字体。

python pdf fonts google-docs pypdf2
1个回答
0
投票

问题是此脚本不处理列表。例如,在Google Docs示例中,在PDF对象中,您会看到以下结构:

{'/Encoding': '/Identity-H', '/Type': '/Font', '/BaseFont': '/Pacifico-Regular', '/ToUnicode': IndirectObject(9, 0), '/DescendantFonts': [IndirectObject(16, 0)], '/Subtype': '/Type0'}

DescendantFonts映射到值列表,如果您更深入地进行搜索,它将包含字体文件的键。您还必须修改脚本以测试数组,例如:

if type(obj) == PyPDF2.generic.ArrayObject:  # You can also do ducktyping here
    for i in obj:
        if hasattr(i, 'keys'):
            walk(i, all_fonts, embedded_fonts)
© www.soinside.com 2019 - 2024. All rights reserved.