I've been looking for code snippets to be able to convert an Infopath view to Html and then use a converter service to create a PDf document. The form is published via InfoPath Forms Services so the export to PDF function is not available.
Inspired by the snippets I've found, I ended up with a nice piece of lean and mean code:
Hereby assuming that the name of the (current) view is equal to the name of the .xsl file in the XSN package.
How to convert Html to PDF:
Inspired by the snippets I've found, I ended up with a nice piece of lean and mean code:
public void CreatePDF_Clicked(object sender, ClickedEventArgs e) { // Create HTML. try { string sourceFileName = null; byte[] sourceFile = null; XPathNavigator root = MainDataSource.CreateNavigator(); string myViewName = this.CurrentView.ViewInfo.Name; string myViewXslFile = myViewName + ".xsl"; XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(ExtractFromPackage(myViewXslFile)); // Generate a temporary HTML file string fileName = Guid.NewGuid().ToString() + ".htm"; string filePath = Path.Combine(Path.GetTempPath(), fileName); using (XmlWriter writer = XmlWriter.Create(filePath)) { // Convert the XML to HTML transform.Transform(root, writer); // writer.Close(); } // Specify the HTML to convert sourceFile = File.ReadAllBytes(filePath); //** etc... } catch { } } public XmlDocument ExtractFromPackage(string fileName) { try { XmlDocument doc = new XmlDocument(); using (Stream stream = Template.OpenFileFromPackage(fileName)) doc.Load(stream); return doc; } catch (Exception ex) { throw new Exception(string.Format("Error extracting '{0}': {1}", fileName, ex.Message), ex); } }
Hereby assuming that the name of the (current) view is equal to the name of the .xsl file in the XSN package.
How to convert Html to PDF:
- Programmatically Converting Web / HTML pages to PDF format
- Printing InfoPath 2007 Web-based Forms to PDF
There is nothing lean about that code... and especially don't do Writer.Close() inside a using statement!
ReplyDeleteThanks John for your feedback.
DeleteWithout the Writer.Close() it's more lean than it was ;-)
This works great for me. All except one field. It is a multi-line textbox. If I copy the inner xml from "root" and paste into a xml file in VS2012, the field shows no line breaks (\n). But is I get the value of that field via the XPath, it has the breaks in it. I have spent a pretty good amount of time trying to set the XmlWriterSettings, but now I think it might be the XPathNavigator. I need the line breaks and I am running short of ideas. Any suggestions?
ReplyDeleteSet (paste) into xml file by using nodeTypedValue property of the XML element
Delete