标签:
iTextSharp是一个常用的PDF库,我们可以使用它来创建、修改PDF文件或对PDF文件进行一些其他额外的操作.本文讲述了如何在上传过程中将文本文件转换成PDF的方法。
基本工作
在开始之前,我们需要从这个URL下载iTextSharp。除此之外,也可以使用”NuGet Package Manager” 将它从NuGet上下载到项目的解决方案中。下面通过屏幕截图来进行讲解。
代码
为了操作简洁,我设计了一个带上传控件和一个按钮的webform。HTML代码如下:
<!DOCTYPE html> 1. <html xmlns="http://www.w3.org/1999/xhtml"> 2. <head runat="server"> 3. <title></title> 4. </head> 5. <body> 6. <form id="form1" runat="server"> 7. <div> 8. <asp:Label ID="lbl" runat="server" Text="Select a file to upload:"></asp:Label> 9. <asp:FileUpload runat="server" ID="fu" /><br /> 10. <asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" /> 11. </div> 12. </form> 13. </body> 14. </html>
后台代码如下:
1. protected void btnUpload_Click(object sender, EventArgs e)
2. {
3. // Check that upload control had file
4. if(fu.HasFile)
5. {
6. // Get the Posted File
7. HttpPostedFile pf = fu.PostedFile;
8. Int32 fileLen;
9. // Get the Posted file Content Length
10. fileLen = fu.PostedFile.ContentLength;
11. // Create a byte array with content length
12. Byte[] Input = new Byte[fileLen];
13. // Create stream
14. System.IO.Stream myStream;
15. // get the stream of uploaded file
16. myStream = fu.FileContent;
17. // Read from the stream
18. myStream.Read(Input, 0, fileLen);
19. // Create a Document
20. Document doc = new Document();
21. // create PDF File and create a writer on it
22. PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(string.Concat(Server.MapPath("~/Pdf/PdfSample"), ".pdf"), FileMode.Create));
23. // open the document
24. doc.Open();
25. // Add the text file contents
26. doc.Add(new Paragraph(System.Text.Encoding.Default.GetString(Input)));
27. // Close the document
28. doc.Close();
29. }
30. }
当运行应用程序时,它将显示一个上传控件和一个上传按钮。转换后,PDF文件就会存储在“PDF”文件夹下。当然在运行应用程序之前,我们需要在解决方案下创建一个命名为“PDF”的文件夹。
输出结果
标签:
原文地址:http://www.cnblogs.com/Yesi/p/5852551.html