public FileStreamResult PDFGenerator()
{
Stream fileStream = GeneratePDF();
HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=form.pdf");
return new FileStreamResult(fileStream, "application/pdf");
}
我也有代码,使我能够采取一个模板 PDF,写文本和图像等(如果你想这样做)。
注意: 必须将 Stream 位置设置为0。
private Stream GeneratePDF()
{
//create your pdf and put it into the stream... pdf variable below
//comes from a class I use to write content to PDF files
MemoryStream ms = new MemoryStream();
byte[] byteInfo = pdf.Output();
ms.Write(byteInfo, 0, byteInfo.Length);
ms.Position = 0;
return ms;
}
public ReportViewModel PopulateData()
{
var attendances = new List<Attendance>
{
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 01).ToString("ddd"),Date = new DateTime(2018, 02, 01).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
new Attendance{ClassName = "absent",Day = new DateTime(2018, 02, 02).ToString("ddd"),Date = new DateTime(2018, 02, 02).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Absent"},
new Attendance{ClassName = "holiday",Day = new DateTime(2018, 02, 03).ToString("ddd"),Date = new DateTime(2018, 02, 03).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Democracy Day"},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 04).ToString("ddd"),Date = new DateTime(2018, 02, 04).ToString("d"),FirstPunch = "09:05:00",LastPunch = "06:30:01",Remarks = ""},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 05).ToString("ddd"),Date = new DateTime(2018, 02, 05).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
new Attendance{ClassName = "leave",Day = new DateTime(2018, 02, 06).ToString("ddd"),Date = new DateTime(2018, 02, 06).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Sick Leave"},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 07).ToString("ddd"),Date = new DateTime(2018, 02, 07).ToString("d"),FirstPunch = "08:35:00",LastPunch = "06:15:01",Remarks = ""}
};
return new ReportViewModel
{
UserInformation = new UserInformation
{
FullName = "Ritesh Man Chitrakar",
Department = "Information Science"
},
StartDate = new DateTime(2018, 02, 01),
EndDate = new DateTime(2018, 02, 07),
AttendanceData = attendances
};
}
然后我们将创建一个下载 pdf 的函数。要下载 pdf,我们将需要创建2个函数。
1. 下载 pdf
2. 浏览 pdf
public ActionResult DownloadPdf()
{
var filename = "attendance.pdf";
/*get the current login cookie*/
var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k]?.Value);
return new ActionAsPdf("PdfView", new
{
startDate = Convert.ToDateTime(Request["StartDate"]),
endDate = Convert.ToDateTime(Request["EndDate"])
})
{
FileName = filename,
/*pass the retrieved cookie inside the cookie option*/
RotativaOptions = {Cookies = cookies}
};
}
public ActionResult PdfView()
{
var reportAttendanceData = PopulateData();
return View(reportAttendanceData);
}