Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hello I wrote this code to extract a list of PDF names.it** then compares to the input of where the PDF data is stored.The current code merges everything in that folder that is in the pdf data i commented out the part where it checks if the filename "starts with" because it's only then merges one of the documents and not all that are specified.

import json
from PyPDF2 import PdfFileMerger
import os

input = 'pdfdata'  
list = os.listdir(input)

with open('pdf.json','r') as jsonfile:

    jason_info =json.load(jsonfile)
    json_data = [jason_info]

for item in json_data:
   for data_item in item['info']:
       jobjects = (data_item.values())#return only values
       informa = ''.join(ll)#string
   
       filemerger = PdfFileMerger()
       for file in dlist: 
       # if file.startswith(informa):           
               
            filemerger.append(file)
            filemerger.write("combinedpdfs.pdf")
         
 filemerger.close()    
question from:https://stackoverflow.com/questions/65934493/combiningpdfs-on-filename

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
93 views
Welcome To Ask or Share your Answers For Others

1 Answer

Does this do what you want it to?

filemerger = PdfFileMerger()

for item in json_data:
    for dicitonary in item['documents']:  # retrieve key & value
        for pdf in dictionary.values():
            if pdf in dlist:
                filemerger.append(pdf)
            else:
                raise ValueError(f'Pdf file {pdf} missing!')

filemerger.write("combinedpdfs.pdf")
filemerger.close()

I moved the filemerger line out of the for block as otherwise you're constantly resetting it. I also removed the for loop which goes through dlist as you can just check if the pdf file is in dlist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...