0

We can easily export pandas dataframe to csv file. Please find the code below:

import pandas as pd

df = pd.read_csv('/Users/ashy/Downloads/weather_data.csv');
df.to_csv('/Users/ashy/Downloads/file1.csv');

Is there an easy way to generate pdf file from dataframe. There isn't any method available to do so. What alternate methods can we use to generate file from a dataframe ? Please let me know.

thanks

Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54
  • Does this answer your question? [Export Pandas DataFrame into a PDF file using Python](https://stackoverflow.com/questions/33155776/export-pandas-dataframe-into-a-pdf-file-using-python) – Chris Jan 03 '23 at 14:52

1 Answers1

0

This method requires the reportlab library to be installed.

The below code should work:

import pandas as pd
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

df = pd.read_csv('/Users/ashy/Downloads/weather_data.csv')

def df_to_pdf(df, filename):
    doc = SimpleDocTemplate(filename, pagesize=letter)
    elements = []
    t = Table(df.values.tolist())
    elements.append(t)
    doc.build(elements)

df_to_pdf(df, '/Users/ashy/Downloads/weather_data.pdf')
Cassano
  • 253
  • 5
  • 36
  • there isn't any to_pfd method available. Pls find the documentation below: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html – Ashy Ashcsi Jan 03 '23 at 15:32
  • getting the following error: AttributeError: 'DataFrame' object has no attribute 'to_pdf' – Ashy Ashcsi Jan 03 '23 at 16:05
  • the above solution works. PDF file is getting generated. Do you know how to preserve table headers and margins. Pls let me know. – Ashy Ashcsi Jan 05 '23 at 08:56