如何将InfoPath表单转换为pdf或word [英] How to convert infopath form into pdf or word

查看:223
本文介绍了如何将InfoPath表单转换为pdf或word的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从C#winform将infopath表单转换为pdf或word?

How to convert infopath form into pdf or word from C# winform?

推荐答案

Microsoft Office InfoPath 2007通过提供填写功能扩展了InfoPath表单的范围通过Web浏览器创建表单,而无需在用户的计算机上安装InfoPath客户端应用程序.此类表单称为基于Web的表单,并使用启用了浏览器的表单模板创建,这些模板已发布到运行InfoPath Forms Services的SharePoint服务器.
便携式文档格式(PDF)是一种用于共享,显示和打印文档的流行且广泛使用的格式.有一个免费的加载项,即2007 Microsoft Office加载项:Microsoft另存为PDF,它与InfoPath客户端应用程序集成在一起,允许用户将视图从表单导出到PDF.您还可以使用InfoPath 2007对象模型以编程方式将表单的当前视图导出到PDF.但是,这两个选项均不适用于基于Web的表单.本文介绍一种技术,使您可以将基于Web的表单转换为PDF,并允许用户将基于Web的表单显示,保存和打印为PDF文档.
要求
[返回顶部]
要完成本文概述的任务,您必须熟悉设计和发布与InfoPath浏览器兼容的表单模板,在InfoPath和Visual Studio中编写C#代码,ASP.NET开发,Windows SharePoint Services 3.0(WSS),InfoPath Forms Services,以及在自定义Web窗体中托管InfoPath 2007窗体编辑环境一文中讨论的主题.
此外,您必须在计算机上安装以下应用程序:
•Microsoft Office InfoPath 2007
•Windows SharePoint Services 3.0
•具有InfoPath Forms Services的Forms Server 2007或Microsoft Office SharePoint Server 2007
•Microsoft Visual Studio 2005
将基于Web的表单打印为PDF的概述
[返回顶部]
InfoPath表单是XML文件,因此要将基于Web的表单打印为PDF,您必须检索该表单的XML并将其转换为PDF.检索基于Web的表单的XML可能是一个挑战,因为此类表单托管在网页的控件中.可以通过以下方式托管基于Web的表单:
1.使用InfoPath Forms Services网页托管表单.
2.创建一个自定义ASP.NET页面以托管该表单.
在这两种情况下,都使用名为XmlFormView的控件将表单托管在网页上.两种方法之间的区别在于,虽然您可以完全控制自己创建的自定义网页,但是由于无法访问InfoPath Forms Services所提供的代码,因此您对该网页的控制程度不同.给你.此外,不建议修改InfoPath Forms Services使用的文件,因为将来Forms Server或Microsoft Office SharePoint Server的升级可能会覆盖这些文件.建议您创建自己的自定义ASP.NET页面,该页面使用XmlFormView控件来承载表单.
XmlFormView控件具有一个名为XmlForm的属性,该属性为您提供了对表单主要数据源的引用,并允许您检索表单的XML.但是,只能在XmlFormView控件的以下事件之一期间访问XmlForm属性:
•初始化
•NotifyHost
•SubmitToHost
•关闭
NotifyHost事件适用于在表单和承载该表单的ASP.NET页面之间建立通信.若要触发NotifyHost事件,必须在表单上字段的事件处理程序中使用XmlForm类的NotifyHost方法.然后,您可以将NotifyHost事件连接到ASP.NET页中的事件处理程序,检索表单的XML,然后将XML转换为PDF.
本文介绍的技术使用NotifyHost方法和事件将基于Web的表单打印为PDF.图1概述了该技术的工作原理,随后的部分将对其进行详细讨论.
图1:将基于Web的表单打印为PDF的概述

创建和发布与浏览器兼容的表单模板
[返回顶部]
要实现本文中讨论的技术,您必须设计一个新的与浏览器兼容的表单模板,或者修改一个现有的模板.本文中使用了图2中所示的表单模板.它与浏览器兼容,并且具有图3所示的Main数据源.表单模板上的Print to PDF按钮控件具有Clicked事件处理程序,其代码如清单1所示.
图2:示例InfoPath表单模板

图3:示例InfoPath表单模板的主要数据源

清单1:按钮控件的Clicked事件处理程序的代码
public void btnPrintToPDF_Clicked(对象发送者,ClickedEventArgs e)
{
NotifyHost("PrintToPDF");
}
由于表单模板包含托管代码,因此在将其发布到运行InfoPath Forms Services的SharePoint服务器并启用浏览器时,必须执行管理员批准的部署.
有关设计和发布与浏览器兼容的表单模板的更多信息,请参见以下文章:
•与浏览器兼容的表单模板的介绍
•将表单模板发布到运行InfoPath Forms Services的服务器
•如何:部署包含表单代码的表单模板
创建自定义ASP.NET页以托管表单模板
[返回顶部]
将表单模板发布到运行InfoPath Forms Services的SharePoint服务器后,必须按照在自定义Web窗体中托管InfoPath 2007表单编辑环境中的文章中的描述创建一个自定义ASP.NET页,以承载表单模板,然后按照以下步骤操作如何从启用InfoPath 2007浏览器的表单模板执行JScr​​ipt代码以将XmlFormView控件的NotifyHost事件连接到事件处理程序中的文章中的步骤2:将NotifyHost事件连接到事件处理程序"中的说明ASP.NET页面.然后,您必须在此事件处理程序中将代码编写为:
3.检索表单的XML并将其存储在Session变量中.
4.导航到ASP.NET页面,该页面将表单打印为PDF.
清单2显示了如何检索表单的XML,如何将XML存储在名为XMLForm的Session变量中,然后使用Response对象的Redirect方法导航到ASP.NET页面,该页面将表单打印为PDF. XmlFormView1是XmlFormView控件的名称,该控件在ASP.NET页上承载InfoPath表单,而XmlFormView1_NotifyHost是挂接到XmlFormView控件的NotifyHost事件的事件处理程序的名称. PrintToPDF.aspx是将表单打印为PDF的ASP.NET页的名称.在此示例中,PrintToPDF.aspx位于站点根目录下名为CustomPage的文件夹中. 清单2:检索和存储表单的XML,并重定向到打印该表单的页面
受保护的void XmlFormView1_NotifyHost(对象发送者,
NotifyHostEventArgs e)
{
如果(XmlFormView1!= null&& XmlFormView1.XmlForm!= null
&& XmlFormView1.XmlForm.MainDataSource!= null)
{
//检索以下形式的XML
字符串xml =
XmlFormView1.XmlForm.MainDataSource.CreateNavigator().OuterXml;

//将表单的XML存储在XmlForm Session变量中
如果(Session ["XmlForm"]!= null)
{
Session.Add("XmlForm",xml);
}
其他
{
Session ["XmlForm"] = xml;
}

//重定向到将表格打印为PDF的页面
Response.Redirect(〜/CustomPage/PrintToPDF.aspx");
}
}
创建一个ASP.NET页面以将表单打印为PDF
[返回顶部]
与在在自定义Web窗体中托管InfoPath 2007窗体编辑环境"一文中添加ASP.NET页以托管窗体的方式相同,您可以添加ASP.NET页以将窗体打印为PDF.您不必将任何控件添加到Web窗体,但必须记住将Web窗体的EnableSessionState属性设置为True.
将表单打印为PDF的ASP.NET页必须首先检索先前保存在Session变量中的表单的XML,从该XML中提取数据,然后使用该数据生成PDF文件.请注意,此处使用Session变量作为在两个网页之间传递数据的方式,即两个网页所在的页面和打印该表格的页面.您可以选择直接从承载表单的页面进行打印,在这种情况下,您无需使用Session变量或单独的页面即可将表单打印为PDF.
检索表单的XML后,可以使用任何可以生成PDF文件的合适库将其转换为PDF.本文中的示例使用名为iTextSharp的库来使用从表单XML提取的数据生成PDF文件.要使用iTextSharp库,必须在Web项目中添加对iTextSharp DLL的引用.关于使用iTextSharp生成PDF文件的讨论不在本文的讨论范围之内,但是如果您想在自己的项目中使用它,建议您查阅在线文档.此外,出于清晰的原因,将XML转换为PDF的代码一直保持简单,但是通过额外的努力或使用其他PDF库,您可以生成更具个性化和专业外观的PDF文档.
您必须导入清单3中所示的名称空间,并使用清单4中的代码从Session变量中检索表单的XML,然后将该XML转换为PDF.将此代码放在打印表单的ASP.NET页的代码后面,并用您自己的表单模板的适当值替换"my"命名空间.
重要
清单4中显示的代码使用如何通过在InfoPath中使用Visual C#以编程方式对文件附件进行编码和解码来描述附件中的InfoPathAttachmentDecoder类,以对附件的Base64编码字符串进行解码并将其转换为字节数组.
构建项目后,别忘了重置IIS服务,以便您的更改将在SharePoint服务器上生效.
清单3:要导入的命名空间
使用System.Text;
使用System.IO;
使用System.Xml;
使用System.Security.Cryptography;
使用iTextSharp.text;
使用iTextSharp.text.pdf;
清单4:ASP.NET页的Page_Load事件处理程序中的代码,该窗体将表单打印为PDF
//从会话变量中检索InfoPath表单的XML
字符串xml =会话["XmlForm"].ToString();

//将InfoPath表单的XML加载到XmlDocument对象中
XmlDocument xmlForm =新的XmlDocument();
xmlForm.LoadXml(xml);

//将表单的"my"命名空间添加到XmlNamespaceManager对象
XmlNamespaceManager xmlNameSpaceMgr =
新的XmlNamespaceManager(
new NameTable());
xmlNameSpaceMgr.AddNamespace("my",
"http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-10-02T08:59:49");

//使用XPath
检索InfoPath表单字段的值 字符串名称= xmlForm.SelectSingleNode("/my:myFields/my:name",
xmlNameSpaceMgr).InnerText;
字符串日期= xmlForm.SelectSingleNode("/my:myFields/my:date",
xmlNameSpaceMgr).InnerText;
字符串照片= xmlForm.SelectSingleNode("/my:myFields/my:photo",
xmlNameSpaceMgr).InnerText;
XmlNodeList islands = xmlForm.SelectNodes(
"/my:myFields/my:group1/my:group2/my:island",
xmlNameSpaceMgr);
//使用iTextSharp构造PDF文档
//创建一个文档对象
文档文档=新文档(PageSize.A4);

//创建一个侦听文档的作家
//并将XML流定向到MemoryStream
使用(MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document,ms);

document.Open();

字体默认字体= FontFactory.GetFont(
FontFactory.HELVETICA,10,Font.NORMAL);
字体标签字体= FontFactory.GetFont(
FontFactory.HELVETICA,10,Font.BOLD);

//添加名称
段落=新段落(15F);
para.Add(new Chunk("Name:",labelFont));
para.Add(new Chunk(name,defaultFont));
document.Add(paragraph);

//添加日期
段落=新段落(15F);
para.Add(new Chunk("Date:",labelFont));
para.Add(new Chunk(date,defaultFont));
document.Add(paragraph);

//添加图片
如果(!String.IsNullOrEmpty(photo))
{
InfoPathAttachmentDecoder dec =
新的InfoPathAttachmentDecoder(照片);
byte []附件= dec.DecodedAttachment;
iTextSharp.text.Image图片=
iTextSharp.text.Image.GetInstance(attachment);
document.Add(image);
}

//添加岛屿
iTextSharp.text.Table表=新的iTextSharp.text.Table(1);
table.Alignment = 0;
table.Cellpadding = 2F;
table.Width = 50F;
table.AddCell(new Cell(new Chunk("Islands",labelFont)));
for(int i = 0; i< islands.Count; i ++)
{
table.AddCell(new Cell(
新块(islands [i] .InnerText,defaultFont)));
}
document.Add(table);

document.Close();

//将InfoPath表单作为PDF文档返回
byte [] data = ms.ToArray();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType =应用程序/pdf";
Response.BinaryWrite(data);
Response.End();

ms.Close();
}
图5中所示的PDF文档是图4中所示的填写的InfoPath表单的XML转换的结果. 图4:Internet Explorer中填写好的InfoPath表单

图5:Internet Explorer中生成的PDF文档
Microsoft Office InfoPath 2007 extended the reach of InfoPath forms by offering the ability to fill out forms through a web browser without requiring the InfoPath client application to be installed on the users'' computers. Such forms are called web-based forms and are created using browser-enabled form templates that are published to a SharePoint server running InfoPath Forms Services.
The Portable Document Format (PDF) is a popular and widely used format for sharing, displaying, and printing documents. There is a free add-in available, 2007 Microsoft Office Add-in: Microsoft Save as PDF, which integrates with the InfoPath client application to allow users to export a view from a form to PDF. You can also use the InfoPath 2007 object model to programmatically export the current view of a form to PDF. However, both these options are not available for web-based forms. This article presents a technique that will enable you to convert web-based forms to PDF and allow users to display, save, and print web-based forms as PDF documents.
Requirements
[ Back To Top ]
To complete the tasks outlined in this article, you must be familiar with designing and publishing InfoPath browser-compatible form templates, writing C# code in InfoPath and Visual Studio, ASP.NET development, Windows SharePoint Services 3.0 (WSS), InfoPath Forms Services, and the topics discussed in the article Hosting the InfoPath 2007 Form Editing Environment in a Custom Web Form.
In addition, you must have the following applications installed on your computer:
• Microsoft Office InfoPath 2007
• Windows SharePoint Services 3.0
• Forms Server 2007 or Microsoft Office SharePoint Server 2007 with InfoPath Forms Services
• Microsoft Visual Studio 2005
Overview of Printing Web-based Forms to PDF
[ Back To Top ]
InfoPath forms are XML files, so to print a web-based form to PDF you must retrieve the XML of the form and convert it to PDF. Retrieving the XML of a web-based form can be a challenge since such forms are hosted in a control on a web page. A web-based form can be hosted by:
1. Using the InfoPath Forms Services web page to host the form.
2. Creating a custom ASP.NET page to host the form.
In both cases, a control named XmlFormView is used to host the form on a web page. The difference between the two methods is that while you have total control over a custom web page that you create, you do not have the same amount of control over the web page that is used by InfoPath Forms Services, since its code-behind is inaccessible to you. In addition, it is not recommended to modify files that are used by InfoPath Forms Services, since they might be overwritten by future upgrades of Forms Server or Microsoft Office SharePoint Server. It is recommended that you create your own custom ASP.NET page, which uses an XmlFormView control to host your forms.
The XmlFormView control has a property named XmlForm, which gives you a reference to the main data source of the form and allows you to retrieve the XML of the form. However, the XmlForm property can only be accessed during one of the following events of the XmlFormView control:
• Initialize
• NotifyHost
• SubmitToHost
• Close
The NotifyHost event is suitable for setting up communication between the form and the ASP.NET page that is hosting it. To trigger the NotifyHost event, you must use the NotifyHost method of the XmlForm class in an event handler of a field on the form. You can then hook up the NotifyHost event to an event handler in the ASP.NET page, retrieve the XML of the form, and convert the XML to PDF.
The technique presented in this article uses the NotifyHost method and event to enable printing web-based forms to PDF. An overview of how this technique works is shown in Figure 1 and is discussed in more detail in subsequent sections.
Figure 1: Overview of printing a web-based form to PDF

Creating and Publishing a Browser-Compatible Form Template
[ Back To Top ]
To implement the technique discussed in this article, you must either design a new browser-compatible form template or modify an existing one. The form template shown in Figure 2 is used throughout this article. It is browser-compatible and has the Main data source shown in Figure 3. The Print to PDF button control on the form template has a Clicked event handler with the code shown in Listing 1.
Figure 2: Sample InfoPath form template

Figure 3: The Main data source of the sample InfoPath form template

Listing 1: Code for the Clicked event handler of the button control
public void btnPrintToPDF_Clicked(object sender, ClickedEventArgs e)
{
NotifyHost("PrintToPDF");
}
Since the form template contains managed code, you will have to perform an administrator-approved deployment when you publish it to a SharePoint server running InfoPath Forms Services, and browser-enable it.
For more information on designing and publishing browser-compatible form templates, see the following articles:
• Introduction to browser-compatible form templates
• Publish a form template to a server running InfoPath Forms Services
• How to: Deploy Form Templates That Contain Form Code
Creating a Custom ASP.NET Page to Host a Form Template
[ Back To Top ]
Once you have published the form template to a SharePoint server running InfoPath Forms Services, you must create a custom ASP.NET page as described in the article Hosting the InfoPath 2007 Form Editing Environment in a Custom Web Form to host the form template and then follow the instructions in "Step 2: Hooking Up the NotifyHost Event to an Event Handler" in the article How to execute JScript code from an InfoPath 2007 browser-enabled form template to hook up the NotifyHost event of the XmlFormView control to an event handler in the ASP.NET page. You must then write code in this event handler to:
3. Retrieve the XML of the form and store it in a Session variable.
4. Navigate to the ASP.NET page that prints the form to PDF.
Listing 2 shows how you can retrieve the XML of the form, store the XML in a Session variable named XMLForm, and then use the Redirect method of the Response object to navigate to the ASP.NET page that prints the form to PDF. XmlFormView1 is the name of the XmlFormView control that is hosting the InfoPath form on the ASP.NET page and XmlFormView1_NotifyHost is the name of the event handler that is hooked up to the NotifyHost event of the XmlFormView control. PrintToPDF.aspx is the name of the ASP.NET page that prints the form to PDF. In this example PrintToPDF.aspx is located in a folder named CustomPage under the root of a site.
Listing 2: Retrieving and storing the XML of a form and redirecting to a page that prints the form
protected void XmlFormView1_NotifyHost(object sender,
NotifyHostEventArgs e)
{
if (XmlFormView1 != null && XmlFormView1.XmlForm != null
&& XmlFormView1.XmlForm.MainDataSource != null)
{
// Retrieve the XML of the form
string xml =
XmlFormView1.XmlForm.MainDataSource.CreateNavigator().OuterXml;

// Store the XML of the form in an XmlForm Session variable
if (Session["XmlForm"] != null)
{
Session.Add("XmlForm", xml);
}
else
{
Session["XmlForm"] = xml;
}

// Redirect to the page that prints the form to PDF
Response.Redirect("~/CustomPage/PrintToPDF.aspx");
}
}
Creating an ASP.NET Page to Print a Form to PDF
[ Back To Top ]
The same way you added the ASP.NET page to host a form in the article Hosting the InfoPath 2007 Form Editing Environment in a Custom Web Form, you can add an ASP.NET page to print a form to PDF. You do not have to add any controls to the web form, but must remember to set the EnableSessionState property of the web form to True.
The ASP.NET page that prints the form to PDF must first retrieve the XML of the form that you previously saved in the Session variable, extract data from this XML, and use the data to generate a PDF file. Please note that the Session variable is used here as a way to pass data between two web pages, that is, the page that hosts the form and the page that prints the form. You can choose to do the printing directly from the page that hosts the form, in which case you do not need to use a Session variable or a separate page to print the form to PDF.
Once you have retrieved the XML of the form, you can convert it to PDF using any suitable library that can generate PDF files. The example in this article uses a library named iTextSharp to generate a PDF file using data that is extracted from the XML of a form. To use the iTextSharp library, you must add a reference to the iTextSharp DLL to your web project. The discussion of using iTextSharp to generate PDF files is beyond the scope of this article, but you are encouraged to consult the online documentation should you want to use it in your own projects. In addition, the code to convert XML to PDF has been kept simple for clarity reasons, but with additional effort or use of another PDF library, you can produce more personalized and professional looking PDF documents.
You must import the namespaces shown in Listing 3 and use the code in Listing 4 to retrieve the XML of the form from the Session variable and then convert this XML to PDF. Place this code in the code-behind of the ASP.NET page that prints the form and replace the "my" namespace with the appropriate value for your own form template.
Important
The code shown in Listing 4 uses the InfoPathAttachmentDecoder class described in the article How to encode and decode a file attachment programmatically by using Visual C# in InfoPath to decode the Base64 encoded string of the attachment and convert it into a byte array.
Do not forget to reset the IIS service after you have built your project so that your changes will take effect on your SharePoint server.
Listing 3: Namespaces to import
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using iTextSharp.text;
using iTextSharp.text.pdf;
Listing 4: Code in Page_Load event handler of the ASP.NET page that prints a form to PDF
// Retrieve XML of InfoPath form from Session variable
string xml = Session["XmlForm"].ToString();

// Load XML of InfoPath form into an XmlDocument object
XmlDocument xmlForm = new XmlDocument();
xmlForm.LoadXml(xml);

// Add the ''my'' namespace of the form to an XmlNamespaceManager object
XmlNamespaceManager xmlNameSpaceMgr =
new XmlNamespaceManager(
new NameTable());
xmlNameSpaceMgr.AddNamespace("my",
"http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-10-02T08:59:49");

// Retrieve the values of the InfoPath form fields using XPath
string name = xmlForm.SelectSingleNode("/my:myFields/my:name",
xmlNameSpaceMgr).InnerText;
string date = xmlForm.SelectSingleNode("/my:myFields/my:date",
xmlNameSpaceMgr).InnerText;
string photo = xmlForm.SelectSingleNode("/my:myFields/my:photo",
xmlNameSpaceMgr).InnerText;
XmlNodeList islands = xmlForm.SelectNodes(
"/my:myFields/my:group1/my:group2/my:island",
xmlNameSpaceMgr);
// Using iTextSharp to construct a PDF document
// Create a document-object
Document document = new Document(PageSize.A4);

// Create a writer that listens to the document
// and directs a XML-stream to a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms);

document.Open();

Font defaultFont = FontFactory.GetFont(
FontFactory.HELVETICA, 10, Font.NORMAL);
Font labelFont = FontFactory.GetFont(
FontFactory.HELVETICA, 10, Font.BOLD);

// Add name
Paragraph paragraph = new Paragraph(15F);
paragraph.Add(new Chunk("Name: ", labelFont));
paragraph.Add(new Chunk(name, defaultFont));
document.Add(paragraph);

// Add date
paragraph = new Paragraph(15F);
paragraph.Add(new Chunk("Date: ", labelFont));
paragraph.Add(new Chunk(date, defaultFont));
document.Add(paragraph);

// Add image
if (!String.IsNullOrEmpty(photo))
{
InfoPathAttachmentDecoder dec =
new InfoPathAttachmentDecoder(photo);
byte[] attachment = dec.DecodedAttachment;
iTextSharp.text.Image image =
iTextSharp.text.Image.GetInstance(attachment);
document.Add(image);
}

// Add islands
iTextSharp.text.Table table = new iTextSharp.text.Table(1);
table.Alignment = 0;
table.Cellpadding = 2F;
table.Width = 50F;
table.AddCell(new Cell(new Chunk("Islands", labelFont)));
for (int i = 0; i < islands.Count; i++)
{
table.AddCell(new Cell(
new Chunk(islands[i].InnerText, defaultFont)));
}
document.Add(table);

document.Close();

// Return the InfoPath form as an PDF document
byte[] data = ms.ToArray();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();

ms.Close();
}
The PDF document shown in Figure 5 is the result of the conversion of the XML of the filled-out InfoPath form shown in Figure 4.
Figure 4: The filled-out InfoPath form in Internet Explorer

Figure 5: The generated PDF document in Internet Explorer


我不知道什么是信息路径表单,但是您可以下载打印为PDF的打印驱动程序,也可以购买PDF库或使用用于控制Word的Office的Microsoft工具.打印驱动程序是获取现有文档并将其转换为PDF的最简单方法.
I have no idea what an infopath form is, but you can download print drivers that print to PDF, and you can buy PDF libraries or use the Microsoft Tools for Office to control Word. A print driver is the easiest way to take an existing document and turn it in to PDF.


这篇关于如何将InfoPath表单转换为pdf或word的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆