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);
}
}
}
}