首页 > 代码库 > MVC 生成PDf表格并插入图片

MVC 生成PDf表格并插入图片

最近做的项目中有一个功能,将最终的个人信息生成PDF表格,并插入图片。对于没接触过的程序员来说回一片茫然,网上有多种生成PDf的方法,我给大家介绍一下我认为比较简单,好操作的一种。

iTextSharp组件

使用方法。

1,引入itextsharp.dll

2,  引入命名空间

 

?
1
2
3
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
?
1
2
3
4
5
6
7
8
9
10
11
12
        Document document = new Document(); <br>           string filepath = "/Upload/Pdf/";
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(filepath));<br>            PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath(filepath + model.ExamNo + ".pdf"), FileMode.Create));<br>       <br>        document.Open();<br>
            BaseFont bftitle = BaseFont.CreateFont(@"C:\\Windows\Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font fonttitle = new Font(bftitle, 20, Font.UNDERLINE);
            BaseFont bf1 = BaseFont.CreateFont(@"C:\\Windows\Fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font1 = new Font(bf1, 12);
            Font fonttitle10 = new Font(bf1, 12);
            Font fonttitle12 = new Font(bf1, 11);
            PdfPCell cellmode = new PdfPCell();<br><span style="color: rgb(255, 0, 0);">  //因为显示照片部分显示5列,而后续部分显示四列,所以创建两个table</span>
          <span style="color: rgb(255, 0, 0);">  PdfPTable table = new PdfPTable(4);
            PdfPTable tablerow = new PdfPTable(5);
</span>

 不一步一步赘述了,将详细代码奉上。

+ View Code?
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public void CreatePersonInfo(RBS.Models.UserConfirmModel model)
       {
           Document document = new Document();
           string filepath = "/Upload/Pdf/";
           Directory.CreateDirectory(HttpContext.Current.Server.MapPath(filepath));
           PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath(filepath + model.ExamNo + ".pdf"), FileMode.Create));
           document.Open();
           BaseFont bftitle = BaseFont.CreateFont(@"C:\\Windows\Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
           Font fonttitle = new Font(bftitle, 20, Font.UNDERLINE);
           BaseFont bf1 = BaseFont.CreateFont(@"C:\\Windows\Fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
           Font font1 = new Font(bf1, 12);
           Font fonttitle10 = new Font(bf1, 12);
           Font fonttitle12 = new Font(bf1, 11);
           PdfPCell cellmode = new PdfPCell();
           PdfPTable table = new PdfPTable(4);
           PdfPTable tablerow = new PdfPTable(5);
           float padding = 0f;
           #region 个人信息<br><span style="color: rgb(255, 0, 0);">//这种写法感觉很像silverlight,一个萝卜一个坑,习惯了html的感觉这样很不适应</span>
           CreateCell(5, 5, 1, "个人信息", fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "考生面试编号", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.ExamNo, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "姓名", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Name, fonttitle10, "left", tablerow);
           CreateCell(model.UserId.ToString(), model.Ext, 0, 1, padding, padding, tablerow);
 
           CreateCell(1, 5, 1, "性别", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Sex == RBS.Models.Gender.Male ? "男" : "女", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "出生日期", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.BirthDate.ToString("yyyy-MM-dd"), fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "身份证号码", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.IdentificationNo, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "户口所在地", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Country, fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "出生地", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.State, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "婚姻状况", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.IsMarrage == RBS.Models.Marriage.Naught ? "未婚" : "已婚", fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "联系地址", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Address, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "邮政编码", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Postcode, fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "联系电话", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Telephone, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "手机", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Mobile, fonttitle10, "left", tablerow);
 
           CreateCell(1, 5, 1, "邮箱", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, model.Email, fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "", fonttitle10, "left", tablerow);
           CreateCell(1, 5, 1, "", fonttitle10, "left", tablerow);
 
 
           #endregion
 
           #region 教育经历
           CreateCell(4, 5, 1, "教育经历", fonttitle10, "left", table);
           CreateCell(4, 5, 1, "教育经历1", fonttitle10, "left", table);
           CreateCell(1, 5, 1, "入学时间", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.EduBegin != null ? Convert.ToDateTime(model.EduBegin).ToString("yyyy-MM-dd") : "", fonttitle10, "left", table);
           CreateCell(1, 5, 1, "毕业时间", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.EduEnd != null ? Convert.ToDateTime(model.EduEnd).ToString("yyyy-MM-dd") : "", fonttitle10, "left", table);
 
           CreateCell(1, 5, 1, "学校名称", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.Graduated, fonttitle10, "left", table);
           CreateCell(1, 5, 1, "专业", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.Specialty, fonttitle10, "left", table);
 
           CreateCell(1, 5, 1, "学历", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.EduBackground, fonttitle10, "left", table);
           CreateCell(1, 5, 1, "学位", fonttitle10, "left", table);
           CreateCell(1, 5, 1, model.Degree, fonttitle10, "left", table);
 
           #endregion
           document.Add(tablerow);
           document.Add(table);
           document.Close();
       }
+ View Code?
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  private void CreateCell(int Colspan, bool Border, string Content, Font font, string alignment, PdfPTable table)
      {
          if (Border)
              CreateCell(Colspan, 0, 1, Content, font, alignment, table);
          else
              CreateCell(Colspan, 0, Content, font, alignment, table);
      }
      ///
      /// 生成单元格
      ///
      /// 合并列数
      /// 间距
      /// 内容
      /// 字体
      /// 对齐方式
      /// 此单元格填充的表
      private void CreateCell(int Colspan, int Padding, string Content, Font font, string alignment, PdfPTable table)
      {
          CreateCell(Colspan, Padding, 0, Content, font, alignment, table);
      }
      ///
      /// 生成单元格
      ///
      /// 合并列数
      /// 间距
      /// 边框线
      /// 内容
      /// 字体
      /// 对齐方式
      /// 此单元格填充的表
      private void CreateCell(int Colspan, int Padding, int Border, string Content, Font font, string alignment, PdfPTable table)
      {
          CreateCell(Colspan, Padding, Border, 0, 0, Content, font, alignment, table);
      }
 
 
      private void CreateCell(int Colspan, int Rowspan, int Padding, int Border, string Content, Font font, string alignment, PdfPTable table)
      {
          CreateCell(Colspan, Rowspan, Padding, Border, 0, 0, Content, font, alignment, table);
      }
 
      ///
      /// 生成单元格
      ///
      /// 合并列数
      /// 间距
      /// 边框线
      /// 水平对齐方式
      /// 垂直对齐方式
      /// 内容
      /// 字体
      /// 对齐方式
      /// 此单元格填充的表
      private void CreateCell(int Colspan, int Padding, int Border, int HorizontalAlignment, int VerticalAlignment, string Content, Font font, string alignment, PdfPTable table)
      {
          PdfPCell cell = new PdfPCell();
          cell.Colspan = Colspan;
          cell.Padding = Padding;
          if (HorizontalAlignment > 0)
              cell.HorizontalAlignment = HorizontalAlignment;
          if (VerticalAlignment > 0)
              cell.VerticalAlignment = VerticalAlignment;
          if (Border == 0)
              cell.Border = Border;
          Paragraph table_t = new Paragraph(Content, font);
          table_t.SetAlignment(alignment);
          cell.AddElement(table_t);
          table.AddCell(cell);
      }
      private void CreateCell(int Colspan, int Rowspan, int Padding, int Border, int HorizontalAlignment, int VerticalAlignment, string Content, Font font, string alignment, PdfPTable table)
      {
          PdfPCell cell = new PdfPCell();
          cell.Colspan = Colspan;
          cell.Rowspan = Rowspan;
          cell.Padding = Padding;
          if (HorizontalAlignment > 0)
              cell.HorizontalAlignment = HorizontalAlignment;
          if (VerticalAlignment > 0)
              cell.VerticalAlignment = VerticalAlignment;
          if (Border == 0)
              cell.Border = Border;
          Paragraph table_t = new Paragraph(Content, font);
          table_t.SetAlignment(alignment);
          cell.AddElement(table_t);
          table.AddCell(cell);
      }
 
    #region 向表格中插入照片,如果向表格中插入照片,这是关键的重载
      /// <param name="imgName">照片名称</param>
      /// <param name="imgExt">照片后缀</param>
      /// <param name="align"></param>
      /// <param name="colSpan"></param>
      /// <param name="padTop"></param>
      /// <param name="padBottom"></param>
      /// <param name="table"></param>
      public void CreateCell(string imgName, string imgExt, int align, int colSpan, float padTop, float padBottom, PdfPTable table)
      {
          PdfPCell cell = new PdfPCell();
          Paragraph ph = new Paragraph();
          string url = HttpContext.Current.Server.MapPath("~/Upload/Images/" + imgName + imgExt + "");
          Image jpg = Image.GetInstance(new Uri(url));
 
      //设置照片的宽度和高度
          jpg.ScaleAbsolute(80, 130);
          Chunk ck = new Chunk(jpg, 4, -4); //图片可设置 偏移
          ph.SetAlignment("right");
          ph.Add(ck);
 
          cell.AddElement(ph);
          if (padTop > 0) { cell.PaddingTop = padTop; }
          if (padBottom > 0) { cell.PaddingBottom = padBottom; }
          if (colSpan > 0) { cell.Colspan = colSpan; }
 
//因为表格插入图片部分需要跨行,为了美观,跨7行,这里需要注意的是,设置几行必须跨几行,否则图片不会显示,当我刚跨2行准备看下效果的时候,pdf照片位置显示空文本框,没有照片,当跨行跟设置的所对应时照片显示出来。
          cell.Rowspan = 7;
          //cell.Border = 0; 设置表格线
          cell.HorizontalAlignment = align;
          table.AddCell(cell);
      }
      #endregion

  

 

 

 附上下载方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static  void DownLoad(string path)
       {
           try
           {
               HttpContext.Current.Response.Charset = "UTF-8";
               HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
               HttpContext.Current.Response.HeaderEncoding = Encoding.UTF8;
               HttpContext.Current.Response.AppendHeader("Content-disposition",
                                             "attachment; filename=" +
                                             HttpUtility.UrlEncode(Path.GetFileName(path), Encoding.UTF8));
               HttpContext.Current.Response.WriteFile(path);
           }
           catch (Exception ex)
           {
               HttpContext.Current.Response.Write("下载文件出错,原因:" + ex.Message);
           }
           finally
           {
               HttpContext.Current.Response.End();
           }
       }

  下载itextpdf.dll