Reading the PDF properties/metadata in Python

浪尽此生 提交于 2020-01-30 15:24:10

问题


How can I read the properties/metadata like Title, Author, Subject and Keywords stored on a PDF file using Python?


回答1:


Try 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.




回答2:


For Python 3 see PyPDF2 with example code from @Khaleel updated to:

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.




回答3:


Note: pyPdf homepage says it is no longer maintained.

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'}



回答4:


For Python 3 and new 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)



回答5:


Try pdfreader You can access document catalog Metadata like below:

   from pdfreader import PDFDocument    
   f = open("foo.pdf", 'rb')
   doc = PDFDocument(f)
   metadata = doc.root.Metadata


来源:https://stackoverflow.com/questions/14209214/reading-the-pdf-properties-metadata-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!