I intend to generate a checksum on the file then I put the checksum as metadata of the file itself. However, the problem I faced was that the checksum generated before and after the metadata was placed in the file is different, I realized that this happened because the metadata in the file was changed. And this is what I did with PyPDF2 in Python 3 :
import os
import sys
import time
import hashlib
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import NameObject, createStringObject
1. Function to generate MD5 Checksum of a file
def md5_checksum(filePath):
try:
with open(filePath, 'rb') as file:
m = hashlib.md5()
while True:
data = file.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
except IOError:
print('[ERROR][NOT FOUND]: ' + filePath)
return 'NULL'
finally:
file.close()
2. Function to embedd metadata to PDF file
def embedd_metadata_file(file_in, file_out, metadatas):
with open(file_in, 'rb') as fin:
pdf = PdfFileReader(fin)
writer = PdfFileWriter()
metadata = writer._info.getObject()
info = pdf.documentInfo
for page in range(pdf.getNumPages()):
writer.addPage(pdf.getPage(page))
for key in info:
metadata.update({NameObject(key): createStringObject(info[key])})
for key in metadatas:
metadata.update({NameObject(key): createStringObject(str(metadatas[key]))})
metadata.update({
NameObject('/Pages'): createStringObject(str(pdf.getNumPages()))
})
with open(file_out, 'wb') as fout:
writer.write(fout)
fin.close()
fout.close()
os.unlink(file_in)
os.rename(file_out, file_in)
pdf = PdfFileReader(open(file_in, 'rb'))
return pdf.getDocumentInfo()
3. Call the function
file = 'example.pdf'
file_in = os.path.join(DIR, file)
file_out = os.path.join(DIR, file + '.OUT.pdf')
checksum = md5_checksum(file_in)
metadata = embedd_metadata_file(file_in, file_out, {
'/MD5Checksum': checksum,
'/ISBN': 'xxx-xxxx-xxxxxxx-xxx',
'/eISBN': 'xxx-xxxx-xxxxxxx-xxx,
'/Title': 'Blablablabla',
'/Size': '2.3 MB',
'/Author': 'Some Author',
'/Copyright': 'Blabla Blablabla',
'/Version': '2',
'/Publisher': 'Blablablabla Blabla'
})
The question is, how can I put the checksum as metadata file without changing the checksum of the file itself? Any help I appreciate it.