標籤:
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”的檔案夾。
輸出結果
ASP.Net中實現上傳過程中將文字檔轉換成PDF的方法