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?
Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of. Column width, the desired column width.
By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With