How to write both returned output and printed output in FPDF?

Viewed 428

I want to write the print statement as well as the returned statement from the code into a pdf file. In other words, I want to write an exact terminal-output into a PDF file. Could anyone help me how to get this?

import fpdf
def oops():
    print('hello')
    return('V')
def data():
    return oops()
pdf = fpdf.FPDF(format = 'A4')
pdf.add_page()
pdf.set_font("Arial")
pdf.cell(10, 10, data())
pdf.output("2.pdf")

I want to write the exact terminal-output into a PDF file. Could anyone help me how to get this?

The expected output in the PDF file is

hello
V
1 Answers

I am not familiar with fpdf or pdf file creations, but here is code that I hope will get you most of the way there using a wrapper function.

Instead of calling print() call the wrapper function print_and_append_to_return_list() which will not only print but also append that value printed to return_list. Any item that you would have returned but not printed, like 'V' in your example, would be directly appended to return_list with this line of code return_list.append('V'). Instead of returning 'V' you would return(return_list) which will contain everything.

It sounds like once you get return_list returned, you already know how to extract data from such a list and insert it into your pdf file.

Here's the code:

return_list = []

def print_and_append_to_return_list(print_string):
    print(print_string)
    return_list.append(print_string)

def oops():
    print_and_append_to_return_list('hello')
    return_list.append('V')
    return(return_list)

data_list = oops()
for item in data_list:
    print(item)
Related