【问题标题】:How to save pdfs如何保存pdf
【发布时间】:2020-09-10 13:09:55
【问题描述】:

如何将 dfa 保存为 pdf? 到目前为止,我能够将每个元素分别保存在每个文件中。现在如何才能将整个文件保存为单个 pdf?

dfa = pd.DataFrame({'STREAM':['EAGLE','HAWK','HAWK','HAWK','EAGLE','HAWK','EAGLE'],'MAT':['A','D','F','D','C','C','E'],'KIS':['B','D','E','D','A','C','D'],'GEO':['B','C','E','E','F','A','B']})

dfa.to_csv('results.csv',index=False)

students_data = csv.reader(open("results.csv", 'r'))

for row in students_data:
    STREAM = row[0]
    MAT = row[1]
    GEO = row[2]
    KIS = row[3]

c = canvas.Canvas(MAT +".pdf")
c.drawString(60, 700, "STREAM:  " + STREAM)
c.drawString(60, 600, "MAT:  " + MAT)
c.drawString(60, 500, "KIS:  " + KIS)
c.drawString(60, 400, "GEO:  " + GEO)
c.save()

【问题讨论】:

标签: python pandas


【解决方案1】:

我的建议是创建一个空白 PDF 作为您的模板页面,然后 将新的 PDF 合并到其中

packet = io.BytesIO()

# Create the initial canvas.
c = canvas.Canvas(packet)

# your code for adding to the canvas

packet.seek(0)
new_pdf = PdfFileReader(packet)
# Import The Template
template = PdfFileReader(open('path_to_template'), "rb")
output = PdfFileWriter()

# add the created PDF as a watermark to the template
page = template.getPage(0)
page.mergePage(new_pdf.getPage(0))

output.addPage(page)
# finally, write "output" to a real file
outputStream = open(output_path, "wb")
output.write(outputStream)
outputStream.close()

您将需要这些导入

from PyPDF2 import PdfFileWriter, PdfFileReader
import io

【讨论】:

  • 请删除template = PdfFileReader(open('path_to_template'), "rb"))中的尾随)
  • 我要导入什么才能让它工作?我已经导入了这个。从 reportlab.pdfgen 导入画布
  • @Ptar 我在底部的答案中包含了导入。
  • 此代码返回此错误 PyPDF2.utils.PdfReadError: Cannot read an empty file
猜你喜欢
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2013-10-04
  • 2011-09-07
相关资源
最近更新 更多