Asp.net MVC学习日记三(以PDF格式输出)

1、首先你要下载一个itextsharp.dll 下载地址http://somewebguy.wordpress.com/2009/05/08/itextsharp-simplify-your-html-to-pdf-creation/

2、在那个网址里面找一个HtmlToPdfBuilder.cs文件,把它引入自己的工程

3、建一个PdfResult类

public class PdfResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{

HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.LETTER);
HtmlPdfPage page1 = builder.AddPage();

page1.AppendHtml("<h1>Order #19807</h1>");
page1.AppendHtml("<p>Andrew Siemer<br>");
page1.AppendHtml("4254 Some Street<br>");
page1.AppendHtml("Los Angeles, CA</p>");
page1.AppendHtml("<table><tr><td><b>Product</b></td><td><b>Price</b></td></tr>");
page1.AppendHtml("<tr><td>ASP.NET MVC Cookbook</td><td>$40.00</td></tr></table>");

byte[] buffer = new byte[4096];
byte[] file = builder.RenderPdf();

HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/pdf";
MemoryStream pdfStream = new MemoryStream(file);
while (true)
{
int read = pdfStream.Read(buffer, 0, buffer.Length);
if (read == 0)
break;
response.OutputStream.Write(buffer, 0, read);
}
response.End();
}
}

4、在HomeController实现一个Action(GetPdf)

public PdfResult GetPdf()
{
return new PdfResult();
}

5、在Index视图里,添加一个连接导向GetPdf

Click <%= Html.ActionLink("here","GetPdf", "Home") %> to get your order in PDF format!

ok,大功完成,happy 一下

你可能感兴趣的:(asp.net)