好库网 好库网首页 | 我的好库
好饱的专栏

C#使用iTextsharp生成PDF

发布者:好饱
发布日期:2011/5/5 16:27:04   更新日期:2011/5/5 16:27:04
阅读次数:10145
评分:4.80
介绍:本文介绍如何使用Asp.net MVC 将生成PDF页面。
正文:

 

如何使用Asp.net MVC 生成PDF页面?

 

首先下载PDF库itextsharp

http://sourceforge.net/projects/itextsharp/

 

 

 

然后将它添加到你的工程中(引用该库)

 

对于ASP.NET MVC模型,添加一个controller然后按下面的代码创建PDF格式数据。

using iTextSharp;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;

public void createPDF()
{
int totalCharCount = 0;

// PDF中使用的字体
Font font8 = FontFactory.GetFont("ARIAL", 7, Font.BOLD);
Font fonttbltxt = FontFactory.GetFont("ARIAL", 7);
Font HeaderFont = FontFactory.GetFont("ARIAL", 12, Font.BOLD);
MemoryStream MStream = new MemoryStream();
Document document = new Document(PageSize.A4,10,10,10,20 );
PdfWriter writer = PdfWriter.GetInstance(document, MStream);
document.Open();

//添加logo
Image logo = Image.GetInstance(Server.MapPath("~/Content/Images/logo.png"));
logo.ScaleToFit(70f, 40f);
document.Add(logo);
Paragraph pgrph = new Paragraph("REPORT", HeaderFont);
pgrph.Alignment = Element.ALIGN_CENTER;
document.Add(pgrph);
PdfContentByte cb = writer.DirectContent;

//表格

PdfPTable tbl = new PdfPTable(4);

PdfPCell pcellID = new PdfPCell(new Phrase(new Chunk("JobID", font8)));
pcellID.Border = 0;
tbl.AddCell(pcellID);
PdfPCell pdfstatus = new PdfPCell(new Phrase(new Chunk("Status", font8)));
pdfstatus.Border = 0;
tbl.AddCell(pdfstatus);
PdfPCell date = new PdfPCell(new Phrase(new Chunk("Date", font8)));
date.Border = 0;
tbl.AddCell(date);
PdfPCell MRN = new PdfPCell(new Phrase(new Chunk("MRN", font8)));
MRN.Border = 0;
tbl.AddCell(MRN);

tbl.TotalWidth = 500;
List jobs = new List();
jobs=jobRepository.GetAllJobs().ToList();
fillCharAndCastData();

// 将数据一个一个填入PDF表格中
foreach (var item in jobs)
{
pcellID = new PdfPCell();
pcellID.Border = 0;
pcellID.AddElement(new Paragraph(Convert.ToString(item.JobCode), fonttbltxt));

tbl.AddCell(pcellID);
pdfstatus = new PdfPCell();
pdfstatus.Border = 0;
pdfstatus.AddElement(new Paragraph(Convert.ToString(item.JobStatus), fonttbltxt));
tbl.AddCell(pdfstatus);
date = new PdfPCell();
date.Border = 0;
date.AddElement(new Paragraph(Convert.ToString(item.JobDate.ToShortDateString()), fonttbltxt));
tbl.AddCell(date);
MRN = new PdfPCell();
MRN.Border = 0;
MRN.AddElement(new Paragraph(Convert.ToString(item.MrnNo), fonttbltxt));
tbl.AddCell(MRN);


}
tbl.WriteSelectedRows(0, 11, 50, 770, cb);
document.Close();
Response.AddHeader("Content-Disposition", "attachment:filename=myPDFNew.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(MStream.GetBuffer());
Response.End();

}

 


评论 [发表评论]
账号 密码 还没帐号呢,现在注册一个?

免责声明:好库网所展示的信息由买卖双方自行提供,其真实性、准确性和合法性由信息发布人负责。好库网不提供任何保证,并不承担任何法律责任。