Ok, here is the code, I have it working now and it is quite cool :-)
My environment is Office 2010 / InfoPath 2010. This is important to know, because for the client machine, on which this function is to be used, a DLL-File needs to be installed into the local assembley, so it can be used by the code at runtime. This is no problem. This Interop-File can be downloaded here:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=938fe8ad-583b-4bd7-a345-23250dc15855
It will be extracted and then you can install it and the client is done. For a larger firm and if you use software distribution, you can have the msi-file distributed automatically.
On Office 2010 clients this would be it. On Office 2007 clients you need to install the PDF-Export Feature that one can get via Word for instance and follow the instructions.
using
Microsoft.Office.Interop.InfoPath;
We need this using declaration. You need to add a reference to the DLL by clicking on "Add Reference" in you project, then go to the COM-Tab and choose Microsoft InfoPath 3.0 Type Library and hit Ok.
So lets say, you want to print a pdf, by clicking on a button, you just create a button and let InfoPath create the necessary clicked-event, the code looks like this:
public void InternalStartup()
{
...
((ButtonEvent)EventManager.ControlEvents["printPDF"]).Clicked += new ClickedEventHandler(printPDF_Clicked);
}
The eventhandler for the button is automatically added to the InternalStartup() Method.
The Method itself needs to look like this:
public void printPDF_Clicked(object sender, ClickedEventArgs e)
{
// Write your code here.
ApplicationClass infopath = null;
XPathNavigator nav = MainDataSource.CreateNavigator();
try
{
infopath = new ApplicationClass();
XDocument doc = infopath.XDocuments.Open(Uri, (int)XdDocumentVersionMode.xdCanOpenInReadOnlyMode);
string savelocation = nav.SelectSingleNode("/my:versuchsbericht/my:administration/my:exportPDF/my:pdfFilePath", NamespaceManager).Value;
doc.View.Export(savelocation, "PDF");
}
catch (Exception ex)
{
nav.SelectSingleNode("/my:versuchsbericht/my:administration/my:exportPDF/my:errorMessage", NamespaceManager).SetValue(ex.ToString());
}
finally
{
//if (infopath != null)
//infopath.ActiveWindow.Close(true);
}
}
The Export-Method wants a filepath, that you can through an xpath in you form, for instance. The Export works, if the File has been saved! So, don't wonder, if you get an error during Preview with an unsaved file.
I have to see, what happens, if I fill out the form with InfoPath 2007, maybe someone else already knows. There is an Interop-DLL-File (I guess you need to add Microsoft InfoPath 2.0 Type Library, I don't know if the 2010-File is backward compatible and solves the whole problem?) , and here is the Download-link for the 2007-interop:
http://www.microsoft.com/downloads/details.aspx?familyid=59daebaa-bed4-4282-a28c-b864d8bfa513&displaylang=en (extract and install ...)
I will post my results here, when I have them.
Best regards
Michael