I found the following code that works fine on a PDF file in the same directory as the python file.
from spire.pdf.common import *
from spire.pdf import *
# Specify the input and output PDF file paths
inputFile = "2021-03-12 AJI-1 signed CR.pdf"
outputFile = "2021-03-12 AJI-1 signed CR.pdf"
# Create an object of the PdfDocument class
doc = PdfDocument()
# Load the PDF file
doc.LoadFromFile(inputFile)
# Flatten the form fields in the file
doc.Form.IsFlatten = True
# Save the resulting file
doc.SaveToFile(outputFile)
doc.Close()
However, I am trying to flatten all PDFs in sub folder So I amended the code as follows:
from spire.pdf.common import *
from spire.pdf import *
import os
import ctypes # An included library with Python install.
mydir = "C:/New folder (5)/testPDFs/"
#mydir = "C:/New folder (5)/testPDFs/*.pdf"
dir_list = os.listdir(mydir)
print(dir_list)
# Create an object of the PdfDocument class
for file in dir_list:
ctypes.windll.user32.MessageBoxW(0, file, "Your title", 1)
inputFile = file
outputFile = file
doc = PdfDocument()
# Load the PDF file
#doc.LoadFromFile(file)
doc.LoadFromFile(mydir + file)
print(mydir + file)
doc.visable=True
# Flatten the form fields in the file
doc.Form.IsFlatten = True
# Save the resulting file
doc.SaveToFile(outputFile)
doc.Close()
When I run this code I get the following error:
Traceback (most recent call last):
File "C:\New folder (5)\flattenGroupTest.py", line 23, in <module>
doc.Form.IsFlatten = True
AttributeError: 'NoneType' object has no attribute 'IsFlatten'
Why will it only work on a file in the current folder, and will it only work on one file?
You need to create and set the
doc
object fields and functions before running the for loop. Here is the adjusted code:I hope you find this helpful.