Skip to content

Instantly share code, notes, and snippets.

@imamdigmi
Last active December 19, 2018 04:47
Show Gist options
  • Select an option

  • Save imamdigmi/920bb5f41b21d223fdee197d3fc96a00 to your computer and use it in GitHub Desktop.

Select an option

Save imamdigmi/920bb5f41b21d223fdee197d3fc96a00 to your computer and use it in GitHub Desktop.
Add/update PDF file metadata
import os
import sys
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import NameObject, createStringObject
DIR = '/home/idiot/Documents'
FILE = 'contoh.pdf'
FILE_IN = os.path.join(DIR, FILE)
FILE_OUT = os.path.join(DIR, 'OUT-' + FILE)
if not os.path.isfile(FILE_IN):
sys.exit("[ERROR][FILE NOT FOUND]: "+FILE_IN)
with open(FILE_IN, 'rb') as fin:
pdf = PdfFileReader(fin)
writer = PdfFileWriter()
metdata = writer._info.getObject()
for page in range(pdf.getNumPages()):
writer.addPage(pdf.getPage(page))
"""Comment up line 22-24 to remove existing metadata"""
info = pdf.documentInfo
for key in info:
metdata.update({NameObject(key): createStringObject(info[key])})
metdata.update({
NameObject('/ISBN'): createStringObject(u'123-12345-1234567-123'),
NameObject('/eISBN'): createStringObject(u'123-12345-1234567-123'),
NameObject('/Title'): createStringObject(u'Judul Buku'),
NameObject('/Size'): createStringObject(u'2376KB'),
NameObject('/Author'): createStringObject(u'Imam, Fendi'),
NameObject('/Pages'): createStringObject(u'204'),
NameObject('/Copyright'): createStringObject(u'Penerbit Gramedia'),
NameObject('/Version'): createStringObject(u'3'),
NameObject('/Publisher'): createStringObject(u'Penerbit Gramedia'),
NameObject('/MD5Checksum'): createStringObject(u'akjhaskjdhaskjdhaskjdhasd')
})
with open(FILE_OUT, 'wb') as fout:
writer.write(fout)
fin.close()
fout.close()
os.unlink(FILE_IN)
os.rename(FILE_OUT, FILE_IN)
"""Show the result"""
pdf = PdfFileReader(open(FILE_IN, 'rb'))
pdf.getDocumentInfo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment