使用iTextSharp生成PDF与生成后直接打开PDF

今天做项目的时候,项目需求要生成PDF打印,整理了一下,分享出来

public ActionResult ExpressSelectedPrint()

BaseFont basefont = BaseFont.CreateFont("C:/Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);设置系统字体

 iTextSharp.text.Font font = new Font(basefont, 12);//设置字体为宋体和大小

 iTextSharp.text.Rectangle mPageSize = new iTextSharp.text.Rectangle(Convert.ToSingle(10 * 72 / 2.54), Convert.ToSingle(6 * 72 / 2.54));//设置打印纸张大小

 iTextSharp.text.Document document = new iTextSharp.text.Document(mPageSize, 0, 0, 0, 0);创建doc对象

 //iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4);调用A4纸大小

 System.IO.MemoryStream stream = new System.IO.MemoryStream();流对象

 PdfWriter.GetInstance(document, stream);
 document.Open();

 document.AddTitle("标题");

 PdfPTable table = new PdfPTable(13);//设置一个TR有多少个TD

 table.WidthPercentage = 100;

PdfPCell cell = new PdfPCell(new Paragraph("第一个PDF", font));

cell.Colspan = 13;

document.Add(table);

document.Close();
byte[] fileBytes = stream.GetBuffer();
stream.Close();
stream.Dispose();
return File(fileBytes, "application/pdf", "第一个PDF" + ".pdf");

}

到这里就完成了第一个PDF

 

如果要直接打开PDF就要调用下面代码

 return new BinaryContentResult(fileBytes, "application/pdf");//返回这一个

 

public class BinaryContentResult : ActionResult
{
private readonly string contentType;
private readonly byte[] contentBytes;
/// <summary>
///
/// </summary>
/// <param name="contentBytes"></param>
/// <param name="contentType"></param>
public BinaryContentResult(byte[] contentBytes, string contentType)
{
this.contentBytes = contentBytes;
this.contentType = contentType;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.Clear();

response.ContentType = this.contentType;

using (var stream = new System.IO.MemoryStream(this.contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
}

posted @ 2017-08-31 17:30  骑着蜗牛的攻城狮  阅读(310)  评论(0)    收藏  举报