6

I am trying to create a PDF generator using C#.NET but having some major difficulties. I have an xml files with the data and an xslt file for the template of the pdf. I tried many different libraries out there but can't seem to get this working properly. Can anyone suggest an example I can use that shows how to do this. Any help would be much appreciated. Thanks

bhavinp
  • 823
  • 1
  • 9
  • 18

1 Answers1

0

I found a solution using the excellent TransformXMLToHTML method by Marc Gravell to transform XML + XSLT to HTML.

The HTML can then be transformed to PDF.

This approach may have been slower than editing a PDF as binary. But it was stable and gave me full control over content quality.

Step 1 - transform XML + XSLT to HTML

I needed to add Nugets including: https://www.nuget.org/packages/System.Xml.ReaderWriter/

using System.Xml;
using System.Xml.Xls;
using System.IO;

public static string TransformXMLToHTML(string inputXml, string xsltString)
{
    XslCompiledTransform transform = new XslCompiledTransform();
    using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
        transform.Load(reader);
    }
    StringWriter results = new StringWriter();
    using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
        transform.Transform(reader, null, results);
    }
    return results.ToString();
}

Step 2 - Transform HTML to PDF

I tried:

All worked and had their weaknesses and strengths.

[Lets not get into a debate about the best C# HTML to PDF converter.]

Stephanie
  • 600
  • 13
  • 24