如何将输出转换为pdf文件

问题描述 投票:0回答:1

如果我有一些函数,在这种情况下,下面是一个计算模式的函数,另一个函数是计算数字列表的平均值,然后打印语句“ Hello World!”。最后打印一个箱形图:

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)

我如何将上面的所有输出(在这种情况下,就是上面代码的输出(即模式,均值,'Hello World!'和boxplot)全部转换为单个pdf文件?

我在Google Stackoverflow上搜索和搜索,但是只能看到有人建议使用pyPDF,reportlab等。但是没有示例代码可以做到这一点。如果有人可以提供一个示例,将代码的上述输出转换为pdf文件,那就太好了。

非常感谢。

python pdf reportlab pypdf pdfdocument
1个回答
0
投票

首先,您需要获取PyPDF(pdf处理库):pip install fpdf那么您可以在该字符串中写入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

这是fpdf库的文档:https://pyfpdf.readthedocs.io/en/latest/

© www.soinside.com 2019 - 2024. All rights reserved.