Search code examples
pythonpython-3.xpymupdfpython-pdfreader

Fields "Created" and "Modified" in Document Properties (PDF) were not displayed


Currently I have merged many PDFs together to create one PDF together. I have added metadata information which includes two fields "Created" and "Modified" but as a result these fields still do not display information. Here's my source code:

import re
import os
import fitz
from datetime import datetime

def importMetaData(path):
    regex = r"^r20ut(\d+)ej(\d+)$"
    r_UM = re.compile(regex)
    extension = [".pdf"]
    now = datetime.now() # current date and time
    date_time = now.strftime("%m/%d/%Y %H:%M:%S %p")
    print("date and time:",date_time)
    Number = ""
    for root, dirs, files in os.walk(path):
        for file in files:
            ext = os.path.splitext(file)[-1].lower()
            f_name = os.path.splitext(file)[0]
            if ext in extension:
                if r_UM.search(f_name) is not None:
                    if root.endswith("thuan1"):
                        Number = dictRNumber["code1"]
                    elif root.endswith("thuan2"):
                        Number = dictRNumber["code2"]
                    else:
                        continue
                    inforPDF=fitz.open(os.path.join(root, file))
                    inforPDF.set_metadata({})
                    inforPDF.set_metadata(
                    {
                        "producer": "Microsoft® Word for Office 365",
                        "author": "Thuan",
                        "modDate": date_time,
                        "title": "Data Analysis",
                        "creationDate": date_time,
                        "creator": "Microsoft® Word for Office 365",
                        "subject": Number
                    })
                    inforPDF.save(os.path.join(root, f_name+".pdf"))

Image

Image

Could you please give me some advice?


Solution

  • I am the maintainer of PyMuPDF.

    It is indeed not necessary to first clear the metadata before they get filled with the ultimately desired values.

    More importantly, there is a PDF-specific datetime format which must be used to ensure all PDF viewers understand it: D:20210207070439-03'00'.

    Also, there is a function in PyMuPDF which delivers the correct value for the current timestamp: fitz.getPDFnow().