不使用pdfkit将Pandas DataFrame保存为PDF文件格式

5
我想将Pandas数据框保存为PDF格式。
import pdfkit as pdf    
config = pdf.configuration(wkhtmltopdf="C:\Program Files\wkhtmltopdin\wkhtmltopdf.exe")
    pdf.from_url('http://google.com', 'out.pdf',configuration=config)
--> not working somehow even though I downloaded wkhtmltopdin on several different locations 

from weasyprint import HTML
HTML(string=pd.read_csv('cor.csv').to_html()).write_pdf("report.pdf")

dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2
--> not working : Tried several times to solve this isseue, but cannot download library

我在stackoverflow和其他网站上尝试了5个以上的软件包和方法,但是无法解决问题。

还有没有更多的软件包可以尝试?这让我很烦恼。

提前感谢。

2个回答

10

一个选择是从以下开始:

df.to_html()

然后使用QT将HTML转换为PDF,步骤如下:
from PyQt4.QtGui import QTextDocument, QPrinter, QApplication

import sys
app = QApplication(sys.argv)

doc = QTextDocument()
location = "c://apython//Jim//html//notes.html"
html = open(location).read()
doc.setHtml(html)

printer = QPrinter()
printer.setOutputFileName("foo.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setPageSize(QPrinter.A4)
printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter)

doc.print_(printer)
print("done!")

我从html to pdf中获取了第二段代码,并进行了测试,结果证明在Mac OSX上运行良好。


6
你考虑过绘制Matplotlib表格,然后导出表格图吗?
import matplotlib.backends.backend_pdf
import matplotlib.pyplot as plt
import pandas as pd

d = {'x{}'.format(i): range(30) for i in range(10)}

table = pd.DataFrame(d)

fig = plt.figure()

ax=fig.add_subplot(111)

cell_text = []
for row in range(len(table)):
    cell_text.append(table.iloc[row])

ax.table(cellText=cell_text, colLabels=table.columns, loc='center')
ax.axis('off')

pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
pdf.savefig(fig)
pdf.close()


我觉得这个东西很简单、高度可定制并且与操作系统无关(据我所知)。我在客户的服务器上实现了这个功能,而不需要下载任何额外的包。

你好,之后你能把数据复制粘贴到Excel中吗? - Xomuama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接