Increase width of a specific column while converting pandas Dataframes to PDF

Viewed 5915

I have pandas dataframes that I am trying to convert into a pdf by first converting it to html. While converting it to html, we have col_space property that helps set column width for all columns of the html table.

some_dataframe.to_html(os.path.abspath(html_output_file_path), index=False, border=1, col_space=100)

But my requirement is that I need to increase the width of a specific column only and not all columns present in the final pdf. Is there a way that I can increase the width of a single column only?

2 Answers

You can exploit .style properety, which provides high grain control over the looks of the resulting HTML. Some CSS knowledge is required, though:

import pandas as pd
import numpy as np
import pdfkit

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
styles = [dict(selector='.col3', props=[('min-width', '300px')]), dict(selector='.data', props=[('min-width', '6em')])]
html = df.style.hide_index().set_table_styles(styles).set_table_attributes('border=3 cellspacing=0').render()

with open(os.path.abspath(html_output_file_path), 'w') as f:
    f.write(html)

pdfkit.from_string(html, os.path.abspath(pdf_output_file_path))

This will generate the following look: enter image description here

This is how you can do it

df = pd.DataFrame({'test': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
             'number': [1, 2]})
df.style.set_properties(subset=['test'], **{'width': '300px'})
new_df=df.style.set_properties(subset=['testt'], **{'width': '300px'})

Render this and save to file

html_df = new_df.hide_index().render()
with open("new_df.html","w") as fp:
    fp.write(html_df)

Pdfkit or any similar library should do trick from now on

Related