Advertisement
Python253

html2pdf

Mar 13th, 2024
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: html2pdf.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts an HTML file (.html) to a PDF file (.pdf).
  10. It uses BeautifulSoup to parse the HTML content and generates a PDF with the prettified HTML.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - FPDF library (install using: pip install fpdf)
  15. - BeautifulSoup library (install using: pip install beautifulsoup4)
  16.  
  17. Usage:
  18. 1. Save this script as 'html2pdf.py'.
  19. 2. Ensure your HTML file ('example.html') is in the same directory as the script.
  20. 3. Install the FPDF library using the command: 'pip install fpdf'
  21. 4. Install the BeautifulSoup library using the command: 'pip install beautifulsoup4'
  22. 5. Run the script.
  23. 6. The converted PDF file ('html2pdf.pdf') will be generated in the same directory.
  24.  
  25. Note: Adjust the 'html_filename' and 'pdf_filename' variables in the script as needed.
  26. """
  27. from fpdf import FPDF
  28. from bs4 import BeautifulSoup
  29.  
  30. def html_to_pdf(html_filename, pdf_filename):
  31.     pdf = FPDF()
  32.     pdf.add_page()
  33.     pdf.set_font("Arial", size=12)
  34.  
  35.     with open(html_filename, 'r') as htmlfile:
  36.         soup = BeautifulSoup(htmlfile, 'html.parser')
  37.         pdf.multi_cell(0, 10, soup.prettify())
  38.  
  39.     pdf.output(pdf_filename)
  40.  
  41. if __name__ == "__main__":
  42.     html_filename = 'example.html'
  43.     pdf_filename = 'html2pdf.pdf'
  44.     html_to_pdf(html_filename, pdf_filename)
  45.     print(f"Converted '{html_filename}' to '{pdf_filename}'.")
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement