正常访问状态! 设为首页 | 加入收藏夹 | 浏览历史  
  http://www.guosp.com
 碧海澜涛居
  海纳百川,有容乃大。壁立千刃,无欲则刚!
 
 
关键词:
  网站首页 | 关于本站 | 技术资料 | 美文日志 | 读书收藏 | 影视收藏 | 软件收藏 | 摄影相册| 留言板 
  技术资料 >> ASP.Net资料库 关闭(快捷键alt+C)
搜索标签: 生成 pdf
asp.net生成pdf文件
[阅读次数:902次]  [发布时间:2014年4月3日]

asp.net生成pdf文件

using System.IO;
using System.Text;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;
using iTextSharp.text;
using iTextSharp.text.pdf;


public partial class example_net_createpdf : System.Web.UI.Page
{
static float pageWidth = 594.0f;
static float pageDepth = 828.0f;
static float pageMargin = 30.0f;
static float fontSize = 20.0f;
static float leadSize = 10.0f;
static StreamWriter pPDF = null;
static MemoryStream mPDF = new MemoryStream();

static void ConvertToByteAndAddtoStream(string strMsg)
{

Byte[] buffer = null;
buffer = ASCIIEncoding.ASCII.GetBytes(strMsg);
mPDF.Write(buffer, 0, buffer.Length);
buffer = null;
}

static string xRefFormatting(long xvalue)
{
string strMsg = xvalue.ToString();
int iLen = strMsg.Length;
if (iLen < 10)
{
StringBuilder s = new StringBuilder();
int i = 10 - iLen;
s.Append('0', i);
strMsg = s.ToString() + strMsg;
}
return strMsg;
}


protected void Page_Load(object sender, EventArgs e)
{

}
protected void btncreatepdf_onClick(object sender, EventArgs e)
{
pPDF= new StreamWriter("D:\\myPDF1.pdf");
ArrayList xRefs = new ArrayList();
//Byte[] buffer=null;
float yPos = 0f;
long streamStart = 0;
long streamEnd = 0;
long streamLen = 0;
string strPDFMessage = null;
//PDF文档头信息
strPDFMessage = "%PDF-1.1\n";
ConvertToByteAndAddtoStream(strPDFMessage);

xRefs.Add(mPDF.Length);
strPDFMessage = "1 0 obj\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "<< /Length 2 0 R >>\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "stream\n";
ConvertToByteAndAddtoStream(strPDFMessage);
////////PDF文档描述
streamStart = mPDF.Length;
//字体
strPDFMessage = "BT\n/F0 " + fontSize + " Tf\n";
ConvertToByteAndAddtoStream(strPDFMessage);
//PDF文档实体高度
yPos = pageDepth - pageMargin;
strPDFMessage = pageMargin + " " + yPos + " Td\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = leadSize + " TL\n";
ConvertToByteAndAddtoStream(strPDFMessage);

//实体内容
strPDFMessage = "(PDF test)Tj\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "ET\n";
ConvertToByteAndAddtoStream(strPDFMessage);
streamEnd = mPDF.Length;
streamLen = streamEnd - streamStart;
strPDFMessage = "endstream\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);
//PDF文档的版本信息
xRefs.Add(mPDF.Length);
strPDFMessage = "2 0 obj\n" + streamLen + "\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);

xRefs.Add(mPDF.Length);
strPDFMessage = "3 0 obj\n<</Type/Page/Parent 4 0 R/Contents 1 0 R>>\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);

xRefs.Add(mPDF.Length);
strPDFMessage = "4 0 obj\n<</Type /Pages /Count 1\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "/Kids[\n3 0 R\n]\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "/Resources<</ProcSet[/PDF/Text]/Font<</F0 5 0 R>> >>\n";
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "/MediaBox [ 0 0 " + pageWidth + " " + pageDepth + " ]\n>>\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);

xRefs.Add(mPDF.Length);
strPDFMessage = "5 0 obj\n<</Type/Font/Subtype/Type1/BaseFont/Courier/Encoding/WinAnsiEncoding>>\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);

xRefs.Add(mPDF.Length);
strPDFMessage = "6 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n";
ConvertToByteAndAddtoStream(strPDFMessage);

streamStart = mPDF.Length;
strPDFMessage = "xref\n0 7\n0000000000 65535 f \n";

for (int i = 0; i < xRefs.Count; i++)
{
strPDFMessage += xRefFormatting((long)xRefs[i]) + " 00000 n \n";
}
ConvertToByteAndAddtoStream(strPDFMessage);
strPDFMessage = "trailer\n<<\n/Size " + (xRefs.Count + 1) + "\n/Root 6 0 R\n>>\n";
ConvertToByteAndAddtoStream(strPDFMessage);

strPDFMessage = "startxref\n" + streamStart + "\n%%EOF\n";
ConvertToByteAndAddtoStream(strPDFMessage);
mPDF.WriteTo(pPDF.BaseStream);

mPDF.Close();
pPDF.Close();


}
private static void CreatePDFheader(string filepath, string headertxt, string footertxt)
{
//创建文档对象
Document document = new Document();
// 创建文档写入实例
PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));

// 添加页脚
HeaderFooter footer = new HeaderFooter(new Phrase(footertxt), true);
footer.Border = Rectangle.NO_BORDER;
document.Footer = footer;

//打开文档内容对象
document.Open();
//创建PDF文档中的字体
BaseFont baseFont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_CACHED);
//根据字体路径和字体大小属性创建字体
Font font = new Font(baseFont, 12);
// 添加页眉
HeaderFooter header = new HeaderFooter(new Phrase(headertxt), false);
document.Header = header;
//设计各页的内容
document.Add(new Paragraph("This is First Page中国", font));
//新添加一个页
document.NewPage();
//第2页中添加文本
document.Add(new Paragraph("This is Second Page台湾", font));
// 重置页面数量
document.ResetPageCount();
//关闭文档对象
document.Close();
}
private static void CreatePDF(string content)
{
Console.WriteLine("Chapter 1 example 1: Hello World");

//Rectangle pageSize = new Rectangle(200,720);
// pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
//Rectangle设置样例
//Rectangle pagesize = PageSize.A4;
//pagesize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
//Document document = new Document(pagesize);

Document document = new Document();


try
{

// PdfWriter.GetInstance(document, new FileStream(@"D:\Chap0101.pdf", FileMode.Create));
PdfWriter.GetInstance(document, new FileStream(@"D:\Create.pdf", FileMode.Create));


// 添加页脚

HeaderFooter footer = new HeaderFooter(new Phrase("Page"), true);
footer.Border = Rectangle.NO_BORDER;
document.Footer = footer;
// step 3: we add some metadata and open the document


document.Open();
// 添加页眉
HeaderFooter header = new HeaderFooter(new Phrase("header"), false);

document.Header = header;


//创建PDF文档中的字体
BaseFont baseFont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_CACHED);
//根据字体路径和字体大小属性创建字体
Font font = new Font(baseFont, 12);


//Paragraph paragraph = new Paragraph();
//paragraph.Alignment = Element.ALIGN_JUSTIFIED;

//for (int i = 0; i < 20; i++)
//{
// paragraph.Add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ");
//}
//document.Add(paragraph);

document.Add(new Paragraph(content, font));

//for (int i = 0; i < 300; i++)
//{
// document.Add(new Paragraph("我是太阳我是月亮我是地球我是神!", font));

//}


}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);

}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);

}

document.Close();


}
//主方法
private static void mmain()
{
Console.WriteLine("Chapter 1 example 1: Hello World");

//Rectangle pageSize = new Rectangle(200,720);
// pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
//Rectangle设置样例
//Rectangle pagesize = PageSize.A4;
//pagesize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
//Document document = new Document(pagesize);

Document document = new Document();


try
{
// PdfWriter.GetInstance(document, new FileStream(@"D:\Chap0101.pdf", FileMode.Create));
PdfWriter.GetInstance(document, new FileStream(@"D:\Chap0101.pdf", FileMode.Create));


// 添加页脚

HeaderFooter footer = new HeaderFooter(new Phrase("Page"), true);
footer.Border = Rectangle.NO_BORDER;
document.Footer = footer;
// step 3: we add some metadata and open the document


document.Open();
// 添加页眉
HeaderFooter header = new HeaderFooter(new Phrase("header"), false);

document.Header = header;


//创建PDF文档中的字体
BaseFont baseFont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_CACHED);
//根据字体路径和字体大小属性创建字体
Font font = new Font(baseFont, 12);


//Paragraph paragraph = new Paragraph();
//paragraph.Alignment = Element.ALIGN_JUSTIFIED;

//for (int i = 0; i < 20; i++)
//{
// paragraph.Add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ");
//}
//document.Add(paragraph);


for (int i = 0; i < 300; i++)
{
document.Add(new Paragraph("我是太阳我是月亮我是地球我是神!", font));

}


}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);

}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);

}

document.Close();


}


protected void btndownload_onServerClick(object sender, EventArgs e)
{
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
GridView1_Bind();

}
private void GridView1_Bind()
{
try
{
string constr = ConfigurationManager.ConnectionStrings["test"].ToString();
SqlConnection connection = null;
if (connection == null)
{
connection = new SqlConnection(constr);
connection.Open();
}
string sql = "select * from T_User";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
SqlParameter[] txmsglist = { };

SqlDataReader sdr;
sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

string content = "";
content += "序号";
content += "\t";
content += "username";
content += "\t";
content += "userpwd";
content += "\r\n";
int i = 0;
while (sdr.Read())
{
//schname,teachername,sendid,classname,mobile,summsg,openstunum,pjnum,note
content += ++i;
content += "\t";
content += " " + sdr["username"].ToString() + " ";
content += "\t";
content += sdr["userpwd"].ToString();

content += "\r\n";
}
sdr.Dispose();
sdr.Close();
Response.Clear();
//Response.ContentType = "application/pdf";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword /application/pdf

//Response.AddHeader("Content-Disposition", "attachment; filename=tzmsgsel" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString() + ".pdf");
//EnableViewState = false;
//System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
//tw.Write(content);
//Response.Write(tw.ToString());

//Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
CreatePDF(content);


}
catch (Exception ee)
{
if (ee.Message.ToString() != "")
{
throw new Exception(ee.Message);
}
}
}
}





本页地址: [复制地址]
该页内容非本站原创 收藏自:http://hi.baidu.com/love_1210/item/b3fec4dcc196f0352a35c761
返回顶部 关闭(快捷键alt+C)
评论统计(0条)| 我要评论
暂无评论内容!
我要评论 
我要评论: 带*部分需要填写
 姓名称呼: * 请填写您的姓名或呢称
联系方式: QQ,MSN,Email都可以,方便交流 (仅管理员可见)
 评论内容: * 不超过100字符,50汉字
验证码:
    
  推荐链接
·QQ/MSN在线交流代码
·webdav漏洞的利用
·[转]网页抓取和防抓取
·从网页导出数据生成Excel后...
·ASP随机读取access数据库并...
·制作windows 2003自动安装盘...
·C#读取Excel遇到无法读取的...
·常用的网站漏洞扫描工具
·Access sql语句创建表及字段...
·网站及服务器常见错误的原因...
·IIS无法启动,发生意外错误...
·使用AspNetPager与GridView...
·实现在线编辑、运行、预览h...
·ASP学习摘要,VBscript函数汇...
·VS2005发布网站与生成网站的...
·Asp.Net页面使用UTF-8乱码解...
·c# 抓取网页分析(一)
·aspx生成静态页面html 例子...
·VS2005调试问题解决方案集锦...
·UserData使用总结
  最近更新  
·Host 'XXX' is not allowed...
·Win2008或IIS7的文件上传大...
·IIS7.0上传文件限制的解决方...
·测试信息2015-03-11
·asp.net中处理图片
·ASP.NET之Web打印-终极解决...
·Asp.net下C#调用Word模版实...
·asp.net下将页面内容导入到...
·asp.net导出为pdf文件
·asp.net生成pdf文件
·FCKeditor 文本编辑器的使用...
·ASP.NET 将数据生成PDF
·asp.net2.0导出pdf文件完美...
·AspJpeg的安装与测试
·JS验证浏览器版本对IE11的支...
  热门浏览  
·IE8和IE9出现“此网页上的问...
·无线路由器密码破解,教你断...
·js替换所有回车换行符
·QQ/MSN在线交流代码
·如何取消键盘上的一些快捷键...
·IE弹出“中国工商银行防钓鱼...
·win7声音小的解决方法
·强制两端对齐的函数或者CSS...
·webdav漏洞的利用
·win7下成功安装sql server ...
·显示器分辨率调的过高导致电...
·天诺时空技术技术论坛
·js验证手机号码格式
·JS展开和收缩效果(二)
·本地计算机上的 MSSQLSERVE...
  碧海澜涛居
网站首页关于本站站长简介开发案例技术资料美文日志摄影相册读书收藏影视收藏留言板
版权所有:碧海澜涛 QQ:410436434 Email:shaopo_guo@163.com 苏ICP备15000526号
免责声明:本站为个人网站,站内所有文字、图片等各类资料均为个人兴趣爱好所收集,不用作任何商业用途,亦不保证资料的真实性,若有因浏览本站内容而导致的各类纠纷,本站也不承担任何责任。本站部分内容来自互联网,如有涉及到您的权益或隐私请联系站长解决。