代码语言:javascript复制
/// <summary>
/// 下载按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
using (var imageStream = new FileStream(MapPath("~/views") "/print.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] bytes = this.StreamToBytes(imageStream);
this.Download(bytes, "pdf");
}
}
/// <summary>
/// 在服务器上生成一个PDF COPY
/// </summary>
private void CreatePDF()
{
var bytes = GetData();
int width = bytes.ToImage().Width;
int height = bytes.ToImage().Height;
Document document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
using (var stream = new FileStream(MapPath("~/views") "/print.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (Stream imageStream = new MemoryStream(bytes))
{
var image = iTextSharp.text.Image.GetInstance(imageStream);
document.Add(image);
}
document.Close();
}
}
/// <summary>
/// 下载到本地
/// </summary>
/// <param name="bytes"></param>
/// <param name="fileType"></param>
public void Download(byte[] bytes ,string fileType)
{
Response.Buffer = true;
// Page.Response.Clear();//清除缓冲区所有内容
Page.Response.ContentType = "application/octet-stream";
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" HttpUtility.UrlEncode("print." fileType));
byte[] file = bytes;
Response.BinaryWrite(file);
Response.Flush();
Response.End();
}
使用第三方dll:iTextSharp 。
这里图片被转成了byte[]放在cache中,如果是本地磁盘上的 则
代码语言:javascript复制var imageStream =newFileStream("test.jpg",FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
这样处理。
页面初始化的时候调用下CreatePDF