ASP.Net中实现上传过程中将文本文件转换成PDF的方法

iTextSharp是一个常用的PDF库,我们可以使用它来创建、修改PDF文件或对PDF文件进行一些其他额外的操作.本文讲述了如何在上传过程中将文本文件转换成PDF的方法。

基本工作

在开始之前,我们需要从这个URL下载iTextSharp。除此之外,也可以使用”NuGet Package Manager” 将它从NuGet上下载到项目的解决方案中。下面通过屏幕截图来进行讲解。

代码

为了操作简洁,我设计了一个带上传控件和一个按钮的webform。HTML代码如下: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html> 
   
<html xmlns="http://www.w3.org/1999/xhtml"
<head runat="server"
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"
        <div> 
            <asp:Label ID="lbl" runat="server" Text="Select a file to upload:"></asp:Label> 
            <asp:FileUpload runat="server" ID="fu" /><br /> 
            <asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" /> 
        </div> 
    </form> 
</body> 
</html> 

 后台代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
protected void btnUpload_Click(object sender, EventArgs e) 
        
            // Check that upload control had file 
            if(fu.HasFile) 
            
                // Get the Posted File 
                HttpPostedFile pf = fu.PostedFile; 
                Int32 fileLen; 
                // Get the Posted file Content Length 
                fileLen = fu.PostedFile.ContentLength; 
                // Create a byte array with content length 
                Byte[] Input = new Byte[fileLen]; 
                // Create stream  
                System.IO.Stream myStream; 
                 // get the stream of uploaded file 
                myStream = fu.FileContent; 
                // Read from the stream 
                myStream.Read(Input, 0, fileLen); 
                // Create a Document 
                Document doc = new Document(); 
                // create PDF File and create a writer on it 
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(string.Concat(Server.MapPath("~/Pdf/PdfSample"), ".pdf"), FileMode.Create)); 
                // open the document 
                doc.Open(); 
                // Add the text file contents  
                doc.Add(new Paragraph(System.Text.Encoding.Default.GetString(Input))); 
                // Close the document 
                doc.Close(); 
            
        

当运行应用程序时,它将显示一个上传控件和一个上传按钮。转换后,PDF文件就会存储在“PDF”文件夹下。当然在运行应用程序之前,我们需要在解决方案下创建一个命名为“PDF”的文件夹。

输出结果

posted @   E-iceblue  阅读(1272)  评论(2编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示