使用Python将Pandas DataFrame导出为PDF文件

时间:2015-10-15 18:21:23

标签: python pdf pandas reportlab pypdf

在Pandas中为数据帧生成PDF的有效方法是什么?

5 个答案:

答案 0 :(得分:5)

首先使用matplotlib绘制图表,然后生成pdf

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

df = pd.DataFrame(np.random.random((10,3)), columns = ("col 1", "col 2", "col 3"))

#https://stackoverflow.com/questions/32137396/how-do-i-plot-only-a-table-in-matplotlib
fig, ax =plt.subplots(figsize=(12,4))
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText=df.values,colLabels=df.columns,loc='center')

#https://stackoverflow.com/questions/4042192/reduce-left-and-right-margins-in-matplotlib-plot
pp = PdfPages("foo.pdf")
pp.savefig(fig, bbox_inches='tight')
pp.close()

参考:

How do I plot only a table in Matplotlib?

Reduce left and right margins in matplotlib plot

答案 1 :(得分:3)

一种方法是使用降价。您可以使用df.to_html()。这会将数据帧转换为html表。从那里你可以将生成的html放入markdown文件(.md)(参见http://daringfireball.net/projects/markdown/basics)。从那里,有一些工具可以将markdown转换为pdf(https://www.npmjs.com/package/markdown-pdf)。

此方法的一个多功能一体工具是使用Atom文本编辑器(https://atom.io/)。在那里你可以使用扩展名,搜索“markdown to pdf”,这将为你进行转换。

注意:最近使用to_html()时,出于某种原因我不得不删除额外的'\ n'字符。我选择使用Atom -> Find -> '\n' -> Replace ""

总的来说这应该可以做到!

答案 2 :(得分:2)

以下是我如何使用sqlite3,pandas和pdfkit

从sqlite数据库中执行此操作
import pandas as pd
import pdfkit as pdf
import sqlite3

con=sqlite3.connect("baza.db")

df=pd.read_sql_query("select * from dobit", con)
df.to_html('/home/linux/izvestaj.html')
nazivFajla='/home/linux/pdfPrintOut.pdf'
pdf.from_file('/home/linux/izvestaj.html', nazivFajla)

答案 3 :(得分:0)

这是一个带有中间pdf文件的解决方案。

该表印刷精美,并带有一些最小的CSS。

pdf转换是通过weasyprint完成的。您需要pip install weasyprint

# Create a pandas dataframe with demo data:
import pandas as pd
demodata_csv = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv'
df = pd.read_csv(demodata_csv)

# Pretty print the dataframe as an html table to a file
intermediate_html = '/tmp/intermediate.html'
to_html_pretty(df,intermediate_html,'Iris Data')
# if you do not want pretty printing, just use pandas:
# df.to_html(intermediate_html)

# Convert the html file to a pdf file using weasyprint
import weasyprint
out_pdf= '/tmp/demo.pdf'
weasyprint.HTML(intermediate_html).write_pdf(out_pdf)

# This is the table pretty printer used above:

def to_html_pretty(df, filename='/tmp/out.html', title=''):
    '''
    Write an entire dataframe to an HTML file
    with nice formatting.
    Thanks to @stackoverflowuser2010 for the
    pretty printer see https://stackoverflow.com/a/47723330/362951
    '''
    ht = ''
    if title != '':
        ht += '<h2> %s </h2>\n' % title
    ht += df.to_html(classes='wide', escape=False)

    with open(filename, 'w') as f:
         f.write(HTML_TEMPLATE1 + ht + HTML_TEMPLATE2)

HTML_TEMPLATE1 = '''
<html>
<head>
<style>
  h2 {
    text-align: center;
    font-family: Helvetica, Arial, sans-serif;
  }
  table { 
    margin-left: auto;
    margin-right: auto;
  }
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  th, td {
    padding: 5px;
    text-align: center;
    font-family: Helvetica, Arial, sans-serif;
    font-size: 90%;
  }
  table tbody tr:hover {
    background-color: #dddddd;
  }
  .wide {
    width: 90%; 
  }
</style>
</head>
<body>
'''

HTML_TEMPLATE2 = '''
</body>
</html>
'''

感谢@ stackoverflowuser2010提供的漂亮打印机,请参阅stackoverflowuser2010的答案https://stackoverflow.com/a/47723330/362951

我没有使用pdfkit,因为我在无头式机器上遇到了一些问题。但是,weasyprint很棒。

答案 4 :(得分:0)

参考这两个我觉得有用的例子:

与 ipynb 保存在同一文件夹中的简单 CSS 代码:

/* includes alternating gray and white with on-hover color */

.mystyle {
    font-size: 11pt; 
    font-family: Arial;
    border-collapse: collapse; 
    border: 1px solid silver;

}

.mystyle td, th {
    padding: 5px;
}

.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}

.mystyle tr:hover {
    background: silver;
    cursor: pointer;
}

python代码:

pdf_filepath = os.path.join(folder,file_pdf)
demo_df = pd.DataFrame(np.random.random((10,3)), columns = ("col 1", "col 2", "col 3"))

table=demo_df.to_html(classes='mystyle')

html_string = f'''
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    {table}
  </body>
</html>
'''

HTML(string=html_string).write_pdf(pdf_filepath, stylesheets=["df_style.css"])

Resulting PDF example