ASP.Net中實現上傳過程中將文字檔轉換成PDF的方法

來源:互聯網
上載者:User

標籤:

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的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.