导入的ItextSharp.dll一定要是较高的版本
数据库表结构
生成的PDF样式
代码:
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 <= || ds.Tables[].Rows.Count <= )
{
return new DataTable();
}
return ds.Tables[];
}
}
}
#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 = ; 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, , , , );
//调用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, );
Font ftitle = new Font(bfChinese, , Font.NORMAL, BaseColor.BLACK);
Font fontRukuHeader = new Font(bfChinese, , Font.NORMAL, BaseColor.BLACK);
Font footerChinese = new Font(bfChinese, , Font.NORMAL, BaseColor.BLACK);
//打开文档
document.Open();
PdfPTable table = new PdfPTable(dt.Columns.Count + );
//设置标题
Paragraph title = new Paragraph("中国信息部", ftitle);
title.Alignment = Element.ALIGN_CENTER;//居中
document.Add(title);
//组部标题
PdfPCell middleCell = new PdfPCell(new Phrase(departmentName + "信息库", fontRukuHeader));
middleCell.Colspan = ;
middleCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
middleCell.PaddingRight = ;
middleCell.PaddingTop = ;
middleCell.PaddingBottom = ;
middleCell.BorderWidthBottom = ;
middleCell.BorderWidthLeft = ;
middleCell.BorderWidthRight = ;
middleCell.BorderWidthTop = ;
table.AddCell(middleCell);
//序号
PdfPCell cellNumber = new PdfPCell(new Phrase("第" + DateTime.Now.ToString("yyyyMMddhhmmss") + "号", footerChinese));
cellNumber.Colspan = ;
cellNumber.PaddingRight = ;
cellNumber.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
cellNumber.BorderWidthTop = ;
cellNumber.BorderWidthRight = ;
cellNumber.BorderWidthBottom = ;
cellNumber.BorderWidthLeft = ;
table.AddCell(cellNumber);
//类别
PdfPCell headerleftCell = new PdfPCell(new Phrase("类别", footerChinese));
headerleftCell.Colspan = ;
headerleftCell.BorderWidthLeft = ;
headerleftCell.BorderWidthRight = ;
headerleftCell.BorderWidthTop = ;
headerleftCell.PaddingBottom = ;
headerleftCell.HorizontalAlignment = ;
headerleftCell.BorderWidth = ;
table.AddCell(headerleftCell); PdfPCell headerMiddleCell = new PdfPCell(new Phrase(DateTime.Now.ToString("yyyy年MM月dd日"), footerChinese));
headerMiddleCell.Colspan = ;
headerMiddleCell.HorizontalAlignment = ;
headerMiddleCell.BorderWidthTop = ;
headerMiddleCell.BorderWidthRight = ;
headerMiddleCell.BorderWidthLeft = ;
headerMiddleCell.PaddingBottom = ;
headerMiddleCell.BorderWidth = ;
table.AddCell(headerMiddleCell); table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.WidthPercentage = ;
for (int i = ; 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 = ;
cell.Colspan = ;//合并一列
cell.Rowspan = + dt.Rows.Count; //合并行
table.AddCell(cell);
table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
for (int i = ; i < dt.Rows.Count; i++)
{
for (int j = ; j < dt.Columns.Count; j++)
{
table.AddCell(new Phrase(dt.Rows[i][j].ToString(), footerChinese));
}
}
//合计一列单元格
PdfPCell lastcell = new PdfPCell(new Phrase(" 合 计 ", footerChinese));
lastcell.Colspan = ;//合并两列
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 = ;//合并两列
footerCell.PaddingLeft = ;
footerCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
table.AddCell(footerCell);
//底部单元格信息 记账
footerCell = new PdfPCell(new Phrase("记账", footerChinese));
footerCell.Colspan = ;
footerCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
table.AddCell(footerCell);
//底部单元格信息 信管人员
footerCell = new PdfPCell(new Phrase("信管人员", footerChinese));
footerCell.Colspan = ;//合并四列
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, , 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 = ; i <= reader.NumberOfPages; i++)
{
Rectangle pageSize = reader.GetPageSizeWithRotation(i);
PdfContentByte pdfpageContents = pdfstamper.GetUnderContent(i);
pdfpageContents.BeginText();
pdfpageContents.SetFontAndSize(bfChinese, );
pdfpageContents.SetRGBColorFill(, , );
float textAngle = 45.0f;
pdfpageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf, pageSize.Width / , pageSize.Height / , textAngle);
pdfpageContents.EndText();
}
pdfstamper.FormFlattening = true;
pdfstamper.Close();
reader.Close();
return stream.ToArray();
}
}
}
}