from io import BytesIO
from xhtml2pdf import pisa
# Open the XML file and read its contents
with open("my_xml_file.xml", "r") as xml_file:
xml_content = xml_file.read()
# Create a new BytesIO object to hold the PDF file's content
pdf_file = BytesIO()
# Use pisa.pisaDocument() to convert the XML file to PDF
result = pisa.pisaDocument(BytesIO(xml_content), pdf_file)
# Check if the conversion was successful
if result.err:
raise ValueError("Failed to convert XML to PDF")
# Save the PDF file to disk
with open("my_pdf_file.pdf", "wb") as f:
f.write(pdf_file.getvalue())