asp.net利用itextsharp生成pdf文档
1最近做系统,需要生成pdf文档,搜索了一下,找到了itextsharp这个开源的用于生成pdf文档的好东东。研究了一下asp.net如何利用它生成pdf文档。代码如下:
2private void CreatPdf()
3 {
4 Document doc = new Document();
5 MemoryStream ms = new MemoryStream();
6 try
7 {
8 PdfWriter writer = PdfWriter.GetInstance(doc, ms);
9 writer.CloseStream = false;
10 doc.Open();
11 doc.Add(new Paragraph("hello word!"));
12 }
13 catch (Exception err)
14 {
15 throw new Exception(err.Message);
16 }
17 finally
18 {
19 doc.Close();
20 ViewPdf(ms);
21 }
22 }
23
24private void ViewPdf(Stream fs)
25 {
26 Response.Clear();
27//中文名的话
28//Response.AppendHeader("Content-Disposition", "attachment;filename=" +
29// HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
30 Response.AddHeader("Content-Disposition", "attachment;FileName=out.pdf");
31 Response.AddHeader("Content-Length", fs.Length.ToString());
32 Response.ContentType = "application/pdf";
33 long fileLength = fs.Length;
34 int size = 10240;//10K一--分块下载,10K为1块
35 byte[] readData = new byte[size];
36 if (size > fileLength)
37 size = Convert.ToInt32(fileLength);
38 long fPos = 0;
39 bool isEnd = false;
40 while (!isEnd)
41 {
42 if ((fPos + size) >= fileLength)
43 {
44 size = Convert.ToInt32(fileLength - fPos);
45 isEnd = true;
46 }
47 readData = new byte[size];
48 fs.Position = fPos;
49 fs.Read(readData, 0, size);
50 Response.BinaryWrite(readData);
51 Response.OutputStream.Flush();
52 fPos += size;
53 }
54 fs.Close();
55 Response.OutputStream.Close();
56 Response.End();//非常重要,没有这句的话,页面的HTML代码将会保存到文件中
57 Response.Close();
58 }
59
60以上代码简单的保存了一个pdf文档,具体的设置pdf文档的格式有待进一步研究。实际使用注意处理异常,呵呵。
61
这个博客详细的介绍了itextsharp的用法:http://www.cnblogs.com/hardrock
利用iTextSharp填写中文(中日韩)PDF表单(完整解决方案)