Transform XML via Python

Transform and load XML into PDF document. Use Aspose.PDF for Python for .NET to modify PDF documents programmatically

How to Transform XML with Python for .NET Library

In order to transform XML into PDF file, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for python-net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Python Package Manager Console

pip install aspose-pdf

Transform XML and load into PDF via Python


You need Aspose.PDF for Python via .NET to try the code in your environment.

  1. Set page parameters.
  2. Upload XSLT file.
  3. Then Load and Transform.

Transform XML into PDF - Python

This sample code shows how to transform XML into PDF File

import aspose.pdf as ap
import xml.etree.ElementTree as ET
from io import BytesIO

def example_xslt_to_pdf():
    data_dir = "C:/tmp/"
    with open("XMLFile1.xml", "r") as xml_file:
        xml_content = xml_file.read()
    with open("XSLTFile1.xslt", "r") as xslt_file:
        xslt_content = xslt_file.read()

    options = ap.HtmlLoadOptions()
    # Set page size to A5
    options.page_info.height = 595
    options.page_info.width = 420

    pdf_document = ap.Document(transform_xml_to_html(xml_content, xslt_content), options)
    pdf_document.save(data_dir + "data_xml.pdf")

def transform_xml_to_html(input_xml, xslt_string):
    transform = ET.XSLT(ET.XML(xslt_string))
    xml_tree = ET.ElementTree(ET.XML(input_xml))
    result_tree = transform(xml_tree)
    html_str = ET.tostring(result_tree, encoding='unicode', method='html')
    return BytesIO(html_str.encode('utf-8'))

example_xslt_to_pdf()