导入的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();
}
}
}
}

利用ItextSharp 生成PDF文档改进版的更多相关文章

  1. qt 利用 HTML 生成PDF文档,不能显示jpg图片

    利用 QPrinter 和html 生成 pdf文档 其中用html语句有显示图片的语句 但只能显示png格式的图片,不能显示jpg格式图片. 经过排查:语法,文件路径等都正确,最终在stack ov ...

  2. iTextSharp生成pdf文档案例

    1.using iTextSharp.text;using iTextSharp.text.pdf; 2.设置页面大小 iTextSharp.text.Rectangle pageSize = new ...

  3. 使用itextsharp创建PDF文档——图片集合

    文档管理系统中 ,扫描模块将文档或证件扫描后.为了便于保存多个图片,拟将多个图片生成一个PDF文档进行保存. 这里我们就需要PDF生成工具了.你可以在这里下载.PDFCreator 主要使用了开源工具 ...

  4. 利用Java动态生成 PDF 文档

    利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...

  5. 如何从Windows Phone 生成PDF文档

    我需要从我的Windows Phone应用程序生成PDF. 遗憾的是没有标准的免费的PDF生成库在Windows Phone上运行. 我不得不自己生成PDF,通过直接写入到文件格式. 这竟然是真的很容 ...

  6. 自动把动态的jsp页面(或静态html)生成PDF文档,并且上传至服务器

    置顶2017年11月06日 14:41:04 阅读数:2311 这几天,任务中有一个难点是把一个打印页面自动给生成PDF文档,并且上传至服务器,然而公司框架只有手动上传文档,打印时可以保存为PDF在本 ...

  7. Aspose.Words操作word生成PDF文档

    Aspose.Words操作word生成PDF文档 using Aspose.Words; using System; using System.Collections.Generic; using ...

  8. 黄聪:利用OpenXml生成Word2007文档(转)

    原文:http://blog.csdn.net/francislaw/article/details/7568317 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 一Op ...

  9. 利用OpenXml生成Word2007文档

    一.OpenXml简介 利用C#生成Word文档并非一定要利用OpenXml技术,至少可以使用微软提供的Office相关组件来编程,不过对于Office2007(确切的说是Word.Excel和Pow ...

随机推荐

  1. Java总结:Java 流(Stream)、文件(File)和IO

    更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...

  2. PHP 在Win下的安装

    1:安装集成环境,Wamp或者Appserv.可以快速搭建测试环境. 2:分别下载安装 下载 PHP 从此处下载免费的 PHP:http://www.php.net/downloads.php 下载 ...

  3. crontab 格式

  4. FPGA视频拼接器的DP 的4k 功能输入, 把lvds 转为 serdes

    4k(3840 x 2160 @60hz)越来越成为一种视频趋势,怎样把4K 接入到拼接器中.是一个棘手的问题. 先看一下原理图的接口: 这是 anx1122的 lvds的接口. 以下看一下系统的框架 ...

  5. java装箱拆箱

    基本数据类型的自动装箱(autoboxing).拆箱(unboxing)是自J2SE 5.0开始提供的功能. 一般我们要创建一个类的对象的时候,我们会这样: Class a = new Class(p ...

  6. VC++程序员如何做好界面

    本屌丝在新春放假期间闲来无事,在各大编程论坛溜达了一圈.发现年前的帖子中,有VC++程序员在界面开发方面遇到了很多苦恼,有抱怨界面工作不好做的,有抱怨用错了界面库的,也有紧急求得技术问题帮助的.看到这 ...

  7. TouchID 指纹解锁

    概述 TouchID 指纹解锁 详细 代码下载:http://www.demodashi.com/demo/10701.html 一.软硬件支持 指纹验证功能的最低硬件支持为iPhone5s, iPa ...

  8. GitLab Notification Emails

    GitLab has a notification system in place to notify a user of events that are important for the work ...

  9. Integer 内部实现

    public static void main(String[] args) { Integer in1 = 128; Integer in2 = 128; System.out.println(in ...

  10. JSON与Bean互转

    转自: 关于json与javaBean之间的转换 废话不多说,直接进入主题,json与javaBean之间的互相转换 javaBean转换成json 直接使用提供的方法可以得到json JSONObj ...