如何在Python中提取PDF元数据?代码示例教程

2021年11月17日03:24:20 发表评论 1,164 次浏览

Python如何提取PDF元数据?本文带你了解如何使用 pikepdf 库从 Python 中的 PDF 文件中提取有用的信息。

如何在Python中提取PDF元数据?PDF 中的元数据是有关 PDF 文档的有用信息,它包括文档标题、作者、最后修改日期、创建日期、主题等等。一些 PDF 文件比其他文件获得更多信息,在本教程中,你将学习如何在 Python 中提取 PDF 元数据。

Python提取PDF元数据示例介绍 - Python 中有很多库和实用程序可以完成同样的事情,但我喜欢使用pikepdf,因为它是一个活跃且维护的库。让我们安装它:

$ pip install pikepdf

Pikepdf 是围绕 C++ QPDF 库的 Pythonic 包装器。让我们将它导入到我们的脚本中:

import pikepdf
import sys

我们还将使用sys模块从命令行参数中获取文件名:

# get the target pdf file from the command-line arguments
pdf_filename = sys.argv[1]

Python如何提取PDF元数据?让我们使用库加载 PDF 文件,并获取元数据:

# read the pdf file
pdf = pikepdf.Pdf.open(pdf_filename)
docinfo = pdf.docinfo
for key, value in docinfo.items():
    print(key, ":", value)

docinfo属性包含文档元数据的字典。这是一个示例执行:

$ python extract_pdf_metadata_simple.py bert-paper.pdf

输出:

/Author : 
/CreationDate : D:20190528000751Z
/Creator : LaTeX with hyperref package
/Keywords :
/ModDate : D:20190528000751Z
/PTEX.Fullbanner : This is pdfTeX, Version 3.14159265-2.6-1.40.17 (TeX Live 2016) kpathsea version 6.2.2
/Producer : pdfTeX-1.40.17
/Subject :
/Title :
/Trapped : /False

这是另一个PDF文件:

$ python extract_pdf_metadata_simple.py python_cheat_sheet.pdf

输出:

/CreationDate : D:20201002181301Z
/Creator : wkhtmltopdf 0.12.5
/Producer : Qt 4.8.7
/Title : Markdown To PDF

如你所见,并非所有文档都具有相同的字段,有些文档包含的信息要少得多。

Python如何提取PDF元数据?请注意,/ModDate/CreationDate分别是 PDF 日期时间格式中的最后修改日期和创建日期。如果你想将此格式转换为 Python 日期时间格式,那么我已从 StackOverflow复制了此代码并对其进行了一些编辑以在 Python 3 上运行,如下是Python提取PDF元数据示例:

import pikepdf
import datetime
import re
from dateutil.tz import tzutc, tzoffset
import sys

pdf_date_pattern = re.compile(''.join([
    r"(D:)?",
    r"(?P<year>\d\d\d\d)",
    r"(?P<month>\d\d)",
    r"(?P<day>\d\d)",
    r"(?P<hour>\d\d)",
    r"(?P<minute>\d\d)",
    r"(?P<second>\d\d)",
    r"(?P<tz_offset>[+-zZ])?",
    r"(?P<tz_hour>\d\d)?",
    r"'?(?P<tz_minute>\d\d)?'?"]))

def transform_date(date_str):
    """
    Convert a pdf date such as "D:20120321183444+07'00'" into a usable datetime
    http://www.verypdf.com/pdfinfoeditor/pdf-date-format.htm
    (D:YYYYMMDDHHmmSSOHH'mm')
    :param date_str: pdf date string
    :return: datetime object
    """
    global pdf_date_pattern
    match = re.match(pdf_date_pattern, date_str)
    if match:
        date_info = match.groupdict()

        for k, v in date_info.items():  # transform values
            if v is None:
                pass
            elif k == 'tz_offset':
                date_info[k] = v.lower()  # so we can treat Z as z
            else:
                date_info[k] = int(v)

        if date_info['tz_offset'] in ('z', None):  # UTC
            date_info['tzinfo'] = tzutc()
        else:
            multiplier = 1 if date_info['tz_offset'] == '+' else -1
            date_info['tzinfo'] = tzoffset(None, multiplier*(3600 * date_info['tz_hour'] + 60 * date_info['tz_minute']))

        for k in ('tz_offset', 'tz_hour', 'tz_minute'):  # no longer needed
            del date_info[k]

        return datetime.datetime(**date_info)

# get the target pdf file from the command-line arguments
pdf_filename = sys.argv[1]
# read the pdf file
pdf = pikepdf.Pdf.open(pdf_filename)
docinfo = pdf.docinfo
for key, value in docinfo.items():
    if str(value).startswith("D:"):
        # pdf datetime format, convert to python datetime
        value = transform_date(str(pdf.docinfo["/CreationDate"]))
    print(key, ":", value)

这是之前的相同输出,但将日期时间格式转换为 Python 日期时间对象:

/Author : 
/CreationDate : 2019-05-28 00:07:51+00:00
/Creator : LaTeX with hyperref package
/Keywords :
/ModDate : 2019-05-28 00:07:51+00:00
/PTEX.Fullbanner : This is pdfTeX, Version 3.14159265-2.6-1.40.17 (TeX Live 2016) kpathsea version 6.2.2
/Producer : pdfTeX-1.40.17
/Subject :
/Title :
/Trapped : /False

如何在Python中提取PDF元数据?从以上的示例,我希望这个快速教程可以帮助你使用 Python 获取 PDF 文档的元数据。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: