Advertisement
Python253

xml2pdf

Mar 16th, 2024
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: xml2pdf.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts an XML file (.xml) to a PDF file (.pdf).
  10. It extracts text content from all elements in the XML and generates a PDF with each text element in a separate cell.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - FPDF library (install using: pip install fpdf)
  15.  
  16. Usage:
  17. 1. Save this script as 'xml2pdf.py'.
  18. 2. Ensure your XML file ('example.xml') is in the same directory as the script.
  19. 3. Install the FPDF library using the command: 'pip install fpdf'
  20. 4. Run the script.
  21. 5. The converted PDF file ('xml2pdf.pdf') will be generated in the same directory.
  22.  
  23. Note: Adjust the 'xml_filename' and 'pdf_filename' variables in the script as needed.
  24. """
  25.  
  26. from fpdf import FPDF
  27. import xml.etree.ElementTree as ET
  28.  
  29. def xml_to_pdf(xml_filename, pdf_filename):
  30.     pdf = FPDF()
  31.     pdf.add_page()
  32.     pdf.set_font("Arial", size=12)
  33.  
  34.     tree = ET.parse(xml_filename)
  35.     root = tree.getroot()
  36.  
  37.     for element in root.iter():
  38.         if element.text:
  39.             pdf.multi_cell(0, 10, element.text)
  40.  
  41.     pdf.output(pdf_filename)
  42.  
  43. if __name__ == "__main__":
  44.     # Set the filenames for the XML and PDF files
  45.     xml_filename = 'example.xml'
  46.     pdf_filename = 'xml2pdf.pdf'
  47.  
  48.     # Convert the XML to a PDF file
  49.     xml_to_pdf(xml_filename, pdf_filename)
  50.  
  51.     print(f"Converted '{xml_filename}' to '{pdf_filename}'.")
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement