导入的ItextSharp.dll一定要是较高的版本
数据库表结构
生成的PDF样式
代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
namespace WebPDF { public partial class _Default : System.Web.UI.Page { /// <summary> /// 初始化加载数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ImportPdf(); } } #region 绑定数据 /// <summary> /// 绑定数据 /// </summary> /// <returns></returns> public DataTable BindData() { string connection = "Data Source = orcl;Persist Security Info=True;User ID=scott;Password=123;Unicode=True"; string oracleSql = "select * from EMP"; using (OracleConnection con = new OracleConnection(connection)) //建立数据库链接 { con.Open(); using (OracleCommand cmd = con.CreateCommand()) { cmd.CommandText = oracleSql; DataSet ds = new DataSet(); OracleDataAdapter da = new OracleDataAdapter(cmd); da.Fill(ds); if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0) { return new DataTable(); } return ds.Tables[0]; } } } #endregion #region 数据格式化 /// <summary> /// 导出PDF格式 /// </summary> public void ImportPdf() { DataTable dt = BindData(); GridView1.DataSource = dt; GridView1.DataBind(); DataTable newdt = new DataTable(); newdt.Columns.Add("编号", typeof(string)); newdt.Columns.Add("名称", typeof(string)); newdt.Columns.Add("职业", typeof(string)); newdt.Columns.Add("薪资", typeof(string)); newdt.Columns.Add("日期", typeof(string)); newdt.Columns.Add("单价", typeof(string)); newdt.Columns.Add("金额", typeof(string)); newdt.Columns.Add("部门号", typeof(string)); decimal deci = 0.00M; for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = newdt.NewRow(); dr["编号"] = dt.Rows[i]["EMPNO"].ToString(); dr["名称"] = dt.Rows[i]["ENAME"].ToString(); dr["职业"] = dt.Rows[i]["JOB"].ToString(); dr["薪资"] = dt.Rows[i]["MGR"].ToString(); dr["日期"] = dt.Rows[i]["HIREDATE"].ToString(); dr["单价"] = dt.Rows[i]["SAL"].ToString(); dr["金额"] = dt.Rows[i]["COMM"].ToString(); dr["部门号"] = dt.Rows[i]["DEPTNO"].ToString(); deci = deci + Decimal.Parse(dt.Rows[i]["COMM"].ToString()); newdt.Rows.Add(dr); } CreatePdf(newdt, deci, "国土资源局"); } #endregion /// <summary> /// 创建PDF文档 /// </summary> /// <param name="dt">table</param> /// <param name="COMM">合计金额</param> /// <param name="departmentName">组部名称副标题</param> public void CreatePdf(DataTable dt, decimal COMM, string departmentName) { //初始化一个目标文档类 Document document = new Document(PageSize.A4, 5, 5, 20, 20); //调用PDF的写入方法流 //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。 PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(HttpContext.Current.Server.MapPath("pdfsample.pdf"), System.IO.FileMode.Create)); //表格列字体 BaseFont bfChinese = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font fontChinese1 = new Font(bfChinese, 10); Font ftitle = new Font(bfChinese, 16, Font.NORMAL, BaseColor.BLACK); Font fontRukuHeader = new Font(bfChinese, 14, Font.NORMAL, BaseColor.BLACK); Font footerChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK); //打开文档 document.Open(); PdfPTable table = new PdfPTable(dt.Columns.Count + 1); //设置标题 Paragraph title = new Paragraph("中国信息部", ftitle); title.Alignment = Element.ALIGN_CENTER;//居中 document.Add(title); //组部标题 PdfPCell middleCell = new PdfPCell(new Phrase(departmentName + "信息库", fontRukuHeader)); middleCell.Colspan = 6; middleCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; middleCell.PaddingRight = 6; middleCell.PaddingTop = 6; middleCell.PaddingBottom = 4; middleCell.BorderWidthBottom = 0; middleCell.BorderWidthLeft = 0; middleCell.BorderWidthRight = 0; middleCell.BorderWidthTop = 0; table.AddCell(middleCell); //序号 PdfPCell cellNumber = new PdfPCell(new Phrase("第" + DateTime.Now.ToString("yyyyMMddhhmmss") + "号", footerChinese)); cellNumber.Colspan = 3; cellNumber.PaddingRight = 6; cellNumber.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cellNumber.BorderWidthTop = 0; cellNumber.BorderWidthRight = 0; cellNumber.BorderWidthBottom = 0; cellNumber.BorderWidthLeft = 0; table.AddCell(cellNumber); //类别 PdfPCell headerleftCell = new PdfPCell(new Phrase("类别", footerChinese)); headerleftCell.Colspan = 4; headerleftCell.BorderWidthLeft = 0; headerleftCell.BorderWidthRight = 0; headerleftCell.BorderWidthTop = 0; headerleftCell.PaddingBottom = 4; headerleftCell.HorizontalAlignment = 0; headerleftCell.BorderWidth = 0; table.AddCell(headerleftCell); PdfPCell headerMiddleCell = new PdfPCell(new Phrase(DateTime.Now.ToString("yyyy年MM月dd日"), footerChinese)); headerMiddleCell.Colspan = 5; headerMiddleCell.HorizontalAlignment = 0; headerMiddleCell.BorderWidthTop = 0; headerMiddleCell.BorderWidthRight = 0; headerMiddleCell.BorderWidthLeft = 0; headerMiddleCell.PaddingBottom = 4; headerMiddleCell.BorderWidth = 0; table.AddCell(headerMiddleCell); table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; table.WidthPercentage = 100; for (int i = 0; i < dt.Columns.Count; i++) { table.AddCell(new Phrase(dt.Columns[i].ColumnName, footerChinese)); } PdfPCell cell = new PdfPCell(new Phrase("此\n联\n交\n资\n源\n部", fontChinese1)); cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ANNOTATION; cell.BorderWidth = 0; cell.Colspan = 1;//合并一列 cell.Rowspan = 3 + dt.Rows.Count; //合并行 table.AddCell(cell); table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.AddCell(new Phrase(dt.Rows[i][j].ToString(), footerChinese)); } } //合计一列单元格 PdfPCell lastcell = new PdfPCell(new Phrase(" 合 计 ", footerChinese)); lastcell.Colspan = 2;//合并两列 lastcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table.AddCell(lastcell); //第二单元格 lastcell = new PdfPCell(new Phrase("", footerChinese)); table.AddCell(lastcell); //第三单元格 lastcell = new PdfPCell(new Phrase("", footerChinese)); table.AddCell(lastcell); //第四单元格 lastcell = new PdfPCell(new Phrase("", footerChinese)); table.AddCell(lastcell); //第五单元格 lastcell = new PdfPCell(new Phrase("", footerChinese)); table.AddCell(lastcell); //第六单元格一列属于 合计值信息 lastcell = new PdfPCell(new Phrase(COMM.ToString(), footerChinese)); lastcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table.AddCell(lastcell); //第七单元格 lastcell = new PdfPCell(new Phrase("", footerChinese)); table.AddCell(lastcell); //底部单元格信息 部门 PdfPCell footerCell = new PdfPCell(new Phrase("部门负责人", footerChinese)); footerCell.Colspan = 2;//合并两列 footerCell.PaddingLeft = 4; footerCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(footerCell); //底部单元格信息 记账 footerCell = new PdfPCell(new Phrase("记账", footerChinese)); footerCell.Colspan = 2; footerCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(footerCell); //底部单元格信息 信管人员 footerCell = new PdfPCell(new Phrase("信管人员", footerChinese)); footerCell.Colspan = 4;//合并四列 footerCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(footerCell); document.Add(table);//文档填充表格信息 document.Close();//关闭文档 //定义一个存储路径的文档名 string fullFileName = System.Web.HttpContext.Current.Server.MapPath("pdfsample.pdf"); Byte[] btArray = WriteToPdf(fullFileName, DateTime.Now.ToString("yyyyMMddhhmmss"), bfChinese); fullFileName = Server.MapPath("pdfsample.pdf"); FileStream fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write); fs.Write(btArray, 0, btArray.Length); fs.Flush(); fs.Close(); fullFileName = Server.MapPath("pdfsample.pdf"); FileInfo downloadFile = new FileInfo(fullFileName); Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=pdfsample.pdf"); Response.AppendHeader("Content-Length", downloadFile.Length.ToString()); System.Web.HttpContext.Current.Response.WriteFile(downloadFile.FullName); Response.WriteFile(downloadFile.FullName); Response.Flush(); Response.End(); } /// <summary> /// 写入pdf文档 /// </summary> /// <param name="sourceFile"></param> /// <param name="stringToWriteToPdf"></param> /// <param name="bfChinese"></param> /// <returns></returns> public static byte[] WriteToPdf(string sourceFile, string stringToWriteToPdf, BaseFont bfChinese) { PdfReader reader = new PdfReader(sourceFile); using (MemoryStream stream = new MemoryStream()) { PdfStamper pdfstamper = new PdfStamper(reader, stream); for (int i = 1; i <= reader.NumberOfPages; i++) { Rectangle pageSize = reader.GetPageSizeWithRotation(i); PdfContentByte pdfpageContents = pdfstamper.GetUnderContent(i); pdfpageContents.BeginText(); pdfpageContents.SetFontAndSize(bfChinese, 40); pdfpageContents.SetRGBColorFill(192, 192, 192); float textAngle = 45.0f; pdfpageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf, pageSize.Width / 2, pageSize.Height / 2, textAngle); pdfpageContents.EndText(); } pdfstamper.FormFlattening = true; pdfstamper.Close(); reader.Close(); return stream.ToArray(); } } } }