Guest User

Untitled

a guest
Mar 18th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. import pandas as pd
  2. import jinja2
  3. import pdfkit
  4. from random import getrandbits, randint
  5.  
  6. # pdfkit is just a wrapper for whktmltopdf. you need to install wkhtml and have it on the path
  7. # alternatively, you can move wkhtmltoimage.exe, wkhtmltopdf.exe and wkhtmltox.dll into the working directory
  8.  
  9. # Create some data
  10. def random_hex(length=10):
  11. return '%0x' % getrandbits(length * 4)
  12.  
  13. df = pd.DataFrame([{"number":randint(0,100),
  14. "name":random_hex(15),
  15. "data1":random_hex(5),
  16. "data2":random_hex(5),
  17. "data3":random_hex(5)} for i in range(10)])[['number','name','data1','data2','data3']]
  18.  
  19. # Don't include the dataframe index in the html output,
  20. # add the appropriate css class, and don't draw the border.
  21. dfhtml = df.to_html(index=False, classes="table-title", border=False)
  22.  
  23. # Load the template
  24. env = jinja2.Environment(loader=jinja2.FileSystemLoader("."))
  25. template = env.get_template("tableTemplate.html")
  26. # pass df, title, message to the template.
  27. html_out = template.render(df=dfhtml,
  28. title="Jinja2 Example",
  29. message="This is an example text input")
  30.  
  31. # write the html to file
  32. with open("output.html", 'wb') as file_:
  33. file_.write(html_out.encode("utf-8"))
  34.  
  35. # write the pdf to file
  36. pdfkit.from_string(html_out, output_path="output.pdf", css=["template.css"])
Add Comment
Please, Sign In to add comment