Programatically Convert InfoPath Form to PDF and Upload to SharePoint
I struggled for a while to find a solution to this issue, so I thought I would share.
What I wanted was an InfoPath form that a user could navigate to, fill out some fields, and when they hit Submit it would take that information and shove it in a pre-canned letter, export it to a PDF and then write that PDF to a SharePoint document library. Once it was in that document library we could do all sorts of cool stuff to it with Workflows.
On the InfoPath side the creation of the form was pretty simple. You start with a blank InfoPath form and create two sections. Name one section “sectionInput” and the other “sectionOutput”. Then add a new data source named “hideInput” with a data type of “True/False (boolean)” with a default value of FALSE to the myFields container.
Now open the properties of your “sectionInput” section, click on the Display tab, then click on the “Conditional Formatting…” button. In the Conditional Formatting window, click Add, then create a rule that say if “hideInput” is equal to “TRUE” to “Hide this control”. Do the same thing to the “sectionOutput” section, but make the control hidden when “hideInput” is FALSE.
Now add your fields and a button to the “sectionInput” section. Copy your pre-canned letter or whatever into the “sectionOutput” section. In the areas of the pre-canned letter that you want to be populated by the fields from the “sectionInput” section, you simply have to add an “Expression Box” control and tie that box to the particular field that you want to display.
Now, right click on the button you created in the sectionInput section and choose “Button Properties…” then click on the “Edit Form Code…” button (make sure you have set up InfoPath to use C# code).
In the new code window, click on Project -> Add Reference and add the Microsoft.Office.Interop.Word 12.0 reference.
Here is a sample of what the full code for the button should look like.
using Microsoft.Office.InfoPath; using Word = Microsoft.Office.Interop.Word; using System; using System.Collections.Generic; using System.Net; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using mshtml; namespace NDA___WM3 { public partial class FormCode { // Member variables are not supported in browser-enabled forms. // Instead, write and read these values from the FormState // dictionary using code such as the following: // // private object _memberVariable // { // get // { // return FormState["_memberVariable"]; // } // set // { // FormState["_memberVariable"] = value; // } // } // NOTE: The following procedure is required by Microsoft Office InfoPath. // It can be modified using Microsoft Office InfoPath. public void InternalStartup() { ((ButtonEvent)EventManager.ControlEvents["buttonSubmit"]).Clicked += new ClickedEventHandler(buttonSubmit_Clicked); } /// /// Declare all variables and assign values to "paramUploadLocation" related variables. /// string paramTempLocation = System.IO.Path.GetTempPath(); string paramUploadLocation = "http://SharePoint/DocumentLibrary/"; string paramFilename; string paramDocFilename; string paramPdfFilename; // string paramExportFilePath; string[] paramMailRecipients = null; XPathNavigator paramHideInputShowOutput; /// /// Create "functionExtractData" function. /// /// This function extracts data from the infopath form and assings to to variables. /// void functionExtractData() { paramHideInputShowOutput = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:hideInput-showOutput", NamespaceManager); } /// /// Create "functionHideInputShowOutput" function. /// /// This function hides the input section and shows the output section. /// void functionHideInputShowOutput() { if (paramHideInputShowOutput != null && paramHideInputShowOutput.ValueAsBoolean == false) { paramHideInputShowOutput.SetValue("true"); } else { MessageBox.Show("There has been an error.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// /// Create "functionExportToDoc" function. /// /// This function exports the current view and creates a DOC file. /// void functionExportToDoc() { /// /// Assign a value to the "paramDocFilename" variable. /// paramFilename = "InfoPathToPDF" + "_" + DateTime.Now.Ticks; paramDocFilename = paramTempLocation + paramFilename + ".doc"; /// /// Export the current view to a DOC file. /// this.CurrentView.Export(paramDocFilename, ExportFormat.Mht); } /// /// Create "functionConvertDocToPDF" function. /// /// This function coverts the DOC file created in the "functionExportToDoc" function to PDF. /// void functionConvertDocToPDF() { /// /// Declare variables /// Word.Application wordApplication = null; Word.Documents wordDocuments = null; Word.Document wordDocument = null; Word.WdExportCreateBookmarks paramCreateBookmarks; Word.WdExportFormat paramExportFormat; Word.WdExportItem paramExportItem; Word.WdExportOptimizeFor paramExportOptimizeFor; Word.WdExportRange paramExportRange; bool paramBitmapMissingFonts; bool paramDocStructureTags; bool paramIncludeDocProps; bool paramKeepIRM; bool paramOpenAfterExport; bool paramUseISO19005_1; int paramStartPage; int paramEndPage; object paramSourceDocPath = null; object paramMissing = null; try { /// /// Assign values to variables. /// wordApplication = new Word.Application(); paramSourceDocPath = paramDocFilename; paramMissing = Type.Missing; paramPdfFilename = paramTempLocation + paramFilename + ".pdf"; paramExportFormat = Word.WdExportFormat.wdExportFormatPDF; paramOpenAfterExport = false; paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint; paramExportRange = Word.WdExportRange.wdExportAllDocument; paramStartPage = 0; paramEndPage = 0; paramExportItem = Word.WdExportItem.wdExportDocumentContent; paramIncludeDocProps = true; paramKeepIRM = true; paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; paramDocStructureTags = true; paramBitmapMissingFonts = true; paramUseISO19005_1 = false; /// /// Invoke new Word application. /// wordApplication = new Word.Application(); wordDocuments = wordApplication.Documents; /// /// Open source DOC file. /// wordDocument = wordDocuments.Open(ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); /// /// Export DOC file to PDF Format. /// if (wordDocument != null) wordDocument.ExportAsFixedFormat(paramPdfFilename, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); } /// /// Display message if exception occurs. /// catch (Exception ex) { MessageBox.Show("An error has occured, please try the operation again. If the error persists, please contact your system administrator.\n" + ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { /// /// Close and release the Document object /// if (wordDocument != null) { wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing); wordDocument = null; } /// /// Quite word and release the ApplicationClass oject /// if (wordApplication != null) { wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null; } /// /// Release the wordApplication. /// Release(wordDocument); Release(wordDocuments); Release(wordApplication); } } /// /// Create "functionFileUpload" function. /// /// This function uploads the specified file to the specified SharePoint site. /// void functionFileUpload(string paramUploadSource, string paramUploadDestination) { WebClient WC = new WebClient(); WC.UseDefaultCredentials = true; byte[] response = WC.UploadFile(paramUploadDestination, "PUT", paramUploadSource); } /// /// Clean up /// public static void Release(object o) { if (o != null && Marshal.IsComObject(o)) { int refCount = 0; do { try { refCount = Marshal.FinalReleaseComObject(o); } catch { } } while (refCount > 0); o = null; } } /// /// Execute Code /// public void buttonSubmit_Clicked(object sender, ClickedEventArgs e) { functionExtractData(); functionHideInputShowOutput(); functionExportToDoc(); functionConvertDocToPDF(); functionFileUpload(paramPdfFilename, paramUploadLocation + paramFilename + ".pdf"); MessageBox.Show("Your form has been successfully submitted.", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Application.ActiveWindow.Close(false); } } }
That should pretty much do it, if you can successfully impliment the code above you will now have an InfoPath form that will convert to PDF and upload itself to a SharePoint document library.
It would be very easy to add additional functionality to the script, like sending an e-mail with the file attached, etc.
C#, Microsoft Office, Programming, SharePoint, System Administration



Recent Comments