InfoPath C# Button: Switch View then Export to PDF

2.5k views Asked by At

I've seen some questions which might be related but don't really answer the question. I've got an InfoPath 2013 form that's being hosted via SharePoint 2013 InfoPath Forms Services. The form has code-behind, and I'm trying to code a button so that it does the following steps:

  1. Switch to a read-only, pre-formatted print view (NOT the default, which is data entry)
  2. Export that view of the form to a PDF
  3. Save the form
  4. Close the form

Through googling, I've found some solutions that get me close but I keep running into issues like thisXDocument not being recognized in the context, or the Export method not being valid. I'm currently using both "Microsoft.Office.Interop.InfoPath" and "Microsoft.Office.Interop.InfoPath.SemiTrust" as references. I'm working in Visual Studio 2012.

Given the requirements above, can this be done via C# code and (if so) what namespaces are needed?

1

There are 1 answers

4
Omegacron On BEST ANSWER

I ultimately ended up with two buttons at the bottom of my form - one for "Save and Close" & one for "Export to PDF". In case it helps anyone else, here is the code for my "Export to PDF" button. The folder location and PDFName are defined within the form (folder location is grabbed dynamically based on where they launched the form from, while PDFName is a concat of other values in the form).

public void CTRL_PDF_Clicked(object sender, ClickedEventArgs e)
    {
        // Write your code here.

        //Declare variables
        string fileName;
        string fileLocation;
        XPathNavigator nameNode;
        XPathNavigator folderNode;
        XPathNavigator timeNode;

        //Get the values for each variable from fields in the form
        nameNode = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:PDFName", NamespaceManager);
        folderNode = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:FolderLocation", NamespaceManager);
        fileName = nameNode.Value;
        fileLocation = folderNode.Value;

        //Export the view as a PDF file.
        Microsoft.Office.InfoPath.View currentView = this.CurrentView;
        this.CurrentView.Export(@fileLocation + fileName + ".pdf", ExportFormat.Pdf);

        // End your code here.
    }

I got around having to switch views by defining my formatted PDF view as the default print view. The Export function apparently works like printing, so it automatically switches to the print view before exporting.