iTextSharp是一个常用的PDF库,我们可以使用它来创建、修改PDF文件或对PDF文件进行一些其他额外的操作.本文讲述了如何在上传过程中将文本文件转换成PDF的方法。
基本工作
在开始之前,我们需要从这个URL下载iTextSharp。除此之外,也可以使用”NuGet Package Manager” 将它从NuGet上下载到项目的解决方案中。下面通过屏幕截图来进行讲解。
代码
为了操作简洁,我设计了一个带上传控件和一个按钮的webform。HTML代码如下:
<!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>
后台代码如下:
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”的文件夹。
输出结果