How to loop through list of values to then create PDFs in Python

40 views Asked by At

I am trying to pull data using urllib and tableau_api_lib to create PDFs based off of filtered data of a view within Tableau. I have THAT part working, but I need help with looping through the list of IDs to then create a dictionary (that is needed to create the PDF), then off of those parameters, create output that changes the PDF name as the same as the ID in the test_loop. I can make it work with just one record (without the loop).

test_loop = ['202','475','78','20','10']

for item in test_loop:
    tableau_filter_value = parse.quote(item)
    pdf_params = {
    "pdf_orientation":"orientation=Landscape",
    "pdf_layout":"type=A4",
    "filter_vendor": f"vf_{tableau_filter_field}={tableau_filter_value}",

}


for params in pdf_params:
    with open('output{test}.pdf'.format(test=params),'wb') as file:
        file.write(conn.query_view_pdf(view_id = pdf_view_id, parameter_dict=params).content)
    

Basically, the PDF should be named as output202.pdf and should have the data associated with it from the pdf_params dict above. So the output, I am expecting 5 different pdfs with this list. I am somewhat new to python, so anything helps!

AttributeError: 'str' object has no attribute 'keys'

++++ tableau_filter_field is defined before this code.

1

There are 1 answers

0
Sowmya On

Firstly, I do not think creating a pdf is similar to creating a .txt file. You cannot create a file called a.pdf and then get a pdf file like how you do with a .txt or .csv or anything else. You might be getting the files created, but they wont be pdf format file, rather a txt file with .pdf extension most probably.

You can check this thread on pdfs - How to create PDF files in Python

Its not surprising that only one record got created since each loop the same dict variable pdf_params is getting overwritten. Instead you can do this.

list_of_params = list()
for item in test_loop:
    tableau_filter_value = parse.quote(item)
    pdf_params = {
    "pdf_orientation":"orientation=Landscape",
    "pdf_layout":"type=A4",
    "filter_vendor": f"vf_{tableau_filter_field}={tableau_filter_value}",

}
    list_of_params.append(pdf_params)

Then you can iterate over list of params to populate to a a file:

for params in list_of_params:
    # write to pdf

for params in pdf_params: in your code actually iterates over the keys of the dict pdf_params, hence the error for str attribute.