How to convert output into a pdf file

2.1k Views Asked by At

Say if I have some functions, in this case below a function which calculates the mode and another function to calculate the mean of a list of numbers, and then followed by printing a statement 'Hello World!' and finally followed by printing a boxplot:

import matplotlib.pyplot as plt
import seaborn as sns

def mode(lst):
    most = max(list(map(lst.count, lst)))
    return print(list(set(filter(lambda x: lst.count(x) == most, lst))))

def mean(lst):
    return print(float(sum(lst)) / max(len(lst), 1))

list1 = [1,2,3,4,5]

mode(list1)
mean(list1)
print('Hello World!')

plt.figure(figsize=(10,10))
sns.boxplot(data=list1)

How do I convert all the output above, in this case the output from the code above (ie. the mode, mean, 'Hello World!' and boxplot) all into a single pdf file?

I have googled around and search around Stackoverflow but can only see people suggesting using pyPDF, reportlab etc. but there is no example code how this can be done. Would be great if someone can provide an example how the above output from the code can be converted into a pdf file.

Many thanks in advance.

1

There are 1 best solutions below

1
On

First you need to get PyPDF (pdf processing library):
pip install fpdf
then you can write strings to this (only strings)

import matplotlib.pyplot as plt
import seaborn as sns
from fpdf import FPDF

def mode(lst):
    most = max(list(map(lst.count, lst)))
    return list(set(filter(lambda x: lst.count(x) == most, lst))) # to write this to pdf you need to return it as a variable and not print it

def mean(lst):
    return float(sum(lst)) / max(len(lst), 1)

list1 = [1,2,3,4,5]

gotmode = mode(list1) #execute functions
gotmean = mean(list1)
helloworld = 'Hello World!'

print(gotmode) #display these variables
print(gotmean)
print(helloworld)


pdf = FPDF() # create pdf
pdf.add_page() #add page!
pdf.set_font("Arial", size=12) # font
pdf.cell(200, 10, txt=str(gotmode), ln=1, align="C") #write to pdf, They need to be strings
pdf.cell(200, 10, txt=str(gotmean), ln=1, align="C")
pdf.cell(200, 10, txt=helloworld, ln=1, align="C")

pdf.output("simple_demo.pdf") # output file

Here is the docs to the fpdf library: https://pyfpdf.readthedocs.io/en/latest/