在 Python 中读取 PDF 属性/元数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14209214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading the PDF properties/metadata in Python
提问by Khaleel
How can I read the properties/metadata like Title, Author, Subject and Keywords stored on a PDF file using Python?
如何使用 Python 读取存储在 PDF 文件中的属性/元数据,如标题、作者、主题和关键字?
采纳答案by namit
Try pdfminer:
试试pdfminer:
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
fp = open('diveintopython.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
print(doc.info) # The "Info" metadata
Here's the output:
这是输出:
>>> [{'CreationDate': 'D:20040520151901-0500',
'Creator': 'DocBook XSL Stylesheets V1.52.2',
'Keywords': 'Python, Dive Into Python, tutorial, object-oriented, programming, documentation, book, free',
'Producer': 'htmldoc 1.8.23 Copyright 1997-2002 Easy Software Products, All Rights Reserved.',
'Title': 'Dive Into Python'}]
For more info, look at this tutorial: A lightweight XMP parser for extracting PDF metadata in Python.
有关更多信息,请查看本教程:用于在 Python 中提取 PDF 元数据的轻量级 XMP 解析器。
回答by Khaleel
Pointed out by Morten Zilmer: pyPdf homepagesays it is no longer maintained.
Morten Zilmer 指出:pyPdf主页说它不再维护。
I have implemented this using pyPdf. Please see the sample code below.
from pyPdf import PdfFileReader
pdf_toread = PdfFileReader(open("doc2.pdf", "rb"))
pdf_info = pdf_toread.getDocumentInfo()
print(str(pdf_info))
Output:
输出:
{'/Title': u'Microsoft Word - Agnico-Eagle - Complaint (00040197-2)', '/CreationDate': u"D:20111108111228-05'00'", '/Producer': u'Acrobat Distiller 10.0.0 (Windows)', '/ModDate': u"D:20111108112409-05'00'", '/Creator': u'PScript5.dll Version 5.2.2', '/Author': u'LdelPino'}
回答by Morten Zilmer
For Python 3 see PyPDF2with example code from @Khaleel updated to:
对于 Python 3,请参阅PyPDF2,其中来自 @Khaleel 的示例代码更新为:
from PyPDF2 import PdfFileReader
pdf_toread = PdfFileReader(open("test.pdf", "rb"))
pdf_info = pdf_toread.getDocumentInfo()
print(str(pdf_info))
Install using pip install PyPDF2.
安装使用pip install PyPDF2.
回答by Rabash
For Python 3 and new pdfminer (pip install pdfminer3k):
对于 Python 3 和新的 pdfminer(pip install pdfminer3k):
import os
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfparser import PDFDocument
fp = open("foo.pdf", 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
parser.set_document(doc)
doc.set_parser(parser)
if len(doc.info) > 0:
info = doc.info[0]
print(info)

