Transform XML via C#

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

How to Transform XML with .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 net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Package Manager Console

PM > Install-Package Aspose.PDF

Transform XML and load into PDF via C#


You need Aspose.PDF for .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 - C#

This sample code shows how to transform XML into PDF File


    private static void ExampleXSLTtoPDF()
    {
        var _dataDir = @"C:\tmp\";
        var XmlContent = File.ReadAllText(@"XMLFile1.xml");
        var XsltContent = File.ReadAllText(@"XSLTFile1.xslt");
        var options = new Aspose.Pdf.HtmlLoadOptions();
        // set page size to A5
        options.PageInfo.Height = 595;
        options.PageInfo.Width = 420;
        var pdfDocument = new Aspose.Pdf.Document(TransformXmltoHtml(XmlContent, XsltContent), options);
        pdfDocument.Save(_dataDir + "data_xml.pdf");
    }

    public static MemoryStream TransformXmltoHtml(string inputXml, string xsltString)
    {
    var transform = new XslCompiledTransform();
    using (var reader = XmlReader.Create(new StringReader(xsltString)))
    {
        transform.Load(reader);
    }
    var memoryStream = new MemoryStream();
    var results = new StreamWriter(memoryStream);
    using (var reader = XmlReader.Create(new StringReader(inputXml)))
    {
        transform.Transform(reader, null, results);
    }
    memoryStream.Position = 0;
    return memoryStream;
    }