DEV Community

Allen Yang
Allen Yang

Posted on

Managing PDF Document Properties and Metadata Using Python

Managing PDF Document Properties and Metadata Using Python

PDF document properties (also known as metadata) contain information such as author, title, subject, and keywords. These fields play a critical role in document management systems—they make documents searchable, classifiable, and traceable. Beyond standard properties, PDF also supports custom properties for storing business-specific extension information. In practice, manually editing properties across hundreds of PDF documents is inefficient and error-prone. By managing these properties programmatically with Python, you can batch-read, set, and validate metadata, automating the document management workflow. This article covers setting standard properties, reading property information, adding custom properties, and setting document expiry dates.

Why Manage Document Properties Programmatically

Compared to manual editing, the programmatic approach offers these advantages:

  • Batch processing: Update author, keywords, and other properties across hundreds of PDF files in one run
  • Data consistency: Define property values in code to eliminate spelling errors and format inconsistencies from manual input
  • Workflow integration: Embed property management into the document generation pipeline, writing metadata automatically at creation time
  • Custom extensions: Store business information (department, project number, classification level) via custom properties for document categorization

Environment Setup

This article uses Spire.PDF for Python, which provides APIs for managing PDF document properties.

pip install Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Once installed, you can import the relevant modules in your Python script and start working.

Setting Standard Document Properties

PDF standard properties include Author, Creator, Keywords, Producer, Subject, and Title. The following code loads a PDF file and sets these properties:

from spire.pdf.common import *
from spire.pdf import *

inputFile = "Input.pdf"
outputFile = "Properties.pdf"

# Load the PDF document
doc = PdfDocument()
doc.LoadFromFile(inputFile)

# Set standard document properties
doc.DocumentInformation.Author = "E-iceblue"
doc.DocumentInformation.Creator = "E-iceblue"
doc.DocumentInformation.Keywords = "pdf, demo, document information"
doc.DocumentInformation.Producer = "Spire.Pdf"
doc.DocumentInformation.Subject = "Demo of Spire.Pdf"
doc.DocumentInformation.Title = "Document Information"

# Set file information
doc.FileInfo.CrossReferenceType = PdfCrossReferenceType.CrossReferenceStream
doc.FileInfo.IncrementalUpdate = False

# Save the document
doc.SaveToFile(outputFile)
doc.Close()
Enter fullscreen mode Exit fullscreen mode

Key steps in the code:

  1. Loading the document: LoadFromFile() loads the PDF document from a file path.
  2. DocumentInformation object: Access and set standard properties through doc.DocumentInformation. Each property is assigned directly.
  3. FileInfo settings: CrossReferenceType controls the cross-reference table storage format (Stream or Table). Setting IncrementalUpdate to False rewrites the entire file on save rather than applying incremental updates.

Reading Document Properties

After setting properties, you typically need to read and verify them. The following code extracts all standard properties from a PDF document:

from spire.pdf.common import *
from spire.pdf import *

inputFile = "Properties.pdf"

doc = PdfDocument()
# Read the PDF file
doc.LoadFromFile(inputFile)

# Get the document information object
docInfo = doc.DocumentInformation

# Read properties one by one
print("Author: " + docInfo.Author)
print("Creation Date: " + docInfo.CreationDate.strftime("%Y/%m/%d %H:%M:%S"))
print("Keywords: " + docInfo.Keywords)
print("Modify Date: " + docInfo.ModificationDate.strftime("%Y/%m/%d %H:%M:%S"))
print("Subject: " + docInfo.Subject)
print("Title: " + docInfo.Title)

doc.Close()
Enter fullscreen mode Exit fullscreen mode

In addition to the manually set properties, the PDF document automatically maintains two timestamps:

  • CreationDate: The document creation time, formatable via strftime()
  • ModificationDate: The last modification time, automatically updated by the PDF writer

Setting Custom Document Properties

Standard properties cover the fields defined by the PDF specification. When you need to store business-specific extension information, custom properties come into play. Custom properties exist as key-value pairs where both the key name and value are freely definable:

from spire.pdf.common import *
from spire.pdf import *

inputFile = "Input.pdf"
outputFile = "CustomDocumentProperties.pdf"

doc = PdfDocument()
# Load the PDF file
doc.LoadFromFile(inputFile)

# Add custom document properties
doc.DocumentInformation.SetCustomProperty("Company", "E-iceblue")
doc.DocumentInformation.SetCustomProperty("Component", "Spire.PDF for .NET")
doc.DocumentInformation.SetCustomProperty("Name", "Daisy")
doc.DocumentInformation.SetCustomProperty("Team", "SalesTeam")

# Save the file
doc.SaveToFile(outputFile, FileFormat.PDF)
doc.Close()
Enter fullscreen mode Exit fullscreen mode

The SetCustomProperty(key, value) method accepts two string parameters: the property name and the property value. Custom properties do not appear in the standard "Document Properties" tab of PDF readers but can be read programmatically, making them suitable for storing business metadata required by document management systems.

Setting Document Expiry Date

In certain scenarios, documents need an expiration date that prompts the user when the document is no longer valid. This can be achieved using a JavaScript Action:

from spire.pdf.common import *
from spire.pdf import *

inputFile = "Input.pdf"
outputFile = "SetExpiryDate.pdf"

doc = PdfDocument()
doc.LoadFromFile(inputFile)

# Build JavaScript script: check if current time exceeds the deadline
javaScript = (
    "var rightNow = new Date();"
    "var endDate = new Date('October 20, 2025 23:59:59');"
    "if(rightNow.getTime() > endDate)"
    "app.alert('This document has expired, please contact us for a new one.', 1);"
    "this.closeDoc();"
)

# Set the JavaScript as the action to execute when the document opens
js = PdfJavaScriptAction(javaScript)
doc.AfterOpenAction = js

# Save the document
doc.SaveToFile(outputFile)
doc.Close()
Enter fullscreen mode Exit fullscreen mode

The AfterOpenAction property specifies a JavaScript action to execute automatically when the document opens. The script above checks the current time on open and, if the deadline has passed, displays an alert and closes the document. This approach is useful for distributing time-sensitive documents.

Practical Tips

Batch Updating Document Properties

When processing large numbers of documents, you can encapsulate property setting in a function and iterate over a directory:

import os

def update_pdf_properties(file_path, author, title, subject, keywords):
    doc = PdfDocument()
    doc.LoadFromFile(file_path)
    doc.DocumentInformation.Author = author
    doc.DocumentInformation.Title = title
    doc.DocumentInformation.Subject = subject
    doc.DocumentInformation.Keywords = keywords
    doc.FileInfo.IncrementalUpdate = False
    doc.SaveToFile(file_path)
    doc.Close()

# Batch update by iterating through a directory
directory = "./pdf_files"
for filename in os.listdir(directory):
    if filename.endswith(".pdf"):
        update_pdf_properties(
            os.path.join(directory, filename),
            author="Company Team",
            title="Quarterly Report",
            subject="Finance",
            keywords="report, 2025, quarterly"
        )
Enter fullscreen mode Exit fullscreen mode

Property Validation and Auditing

In document management systems, checking property completeness is a common requirement:

def validate_pdf_properties(file_path):
    doc = PdfDocument()
    doc.LoadFromFile(file_path)
    info = doc.DocumentInformation
    missing = []
    if not info.Author:
        missing.append("Author")
    if not info.Title:
        missing.append("Title")
    if not info.Keywords:
        missing.append("Keywords")
    doc.Close()
    return missing if missing else "All required properties are set."
Enter fullscreen mode Exit fullscreen mode

By checking whether properties are empty, you can quickly filter out documents with incomplete metadata, ensuring all required information is filled in before archiving.

Conclusion

This article covered the complete workflow for managing PDF document properties and metadata using Python, including setting standard properties, reading property information, adding custom properties, and setting document expiry dates.

Key takeaways:

  1. Use the doc.DocumentInformation object to set and read standard properties (Author, Title, Subject, Keywords, etc.)
  2. Use SetCustomProperty(key, value) to add business-specific custom properties
  3. CreationDate and ModificationDate are automatically maintained by the system and can be formatted via strftime()
  4. Use PdfJavaScriptAction with AfterOpenAction to implement document expiry date control

With these skills, you can integrate property management into your document processing pipeline, enabling batch setting, validation, and auditing of PDF metadata to improve document management standardization and efficiency.

Top comments (0)