aus*_*esr 7 asp.net asp.net-mvc
我正在使用FileResult作为MVC中返回PDF文件的函数的返回值.
我应该在Web窗体中使用什么返回类型?
谢谢
public FileResult PrintPDFVoucher(object sender, EventArgs e)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
outputDoc.Save(memory, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
var result = new FileContentResult(memory.GetBuffer(), "text/pdf");
result.FileDownloadName = "file.pdf";
return result;
}
Run Code Online (Sandbox Code Playgroud)
在ASP.NET Webforms中,您需要手动将文件写入Response流.webforms中没有结果抽象.
Response.ContentType = "Application/pdf";
//Write the generated file directly to the response stream
Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download
Response.End();
Run Code Online (Sandbox Code Playgroud)
此代码未经过测试,但这应该可以帮助您完成大方向.
经典 ASP.NET 没有返回类型的概念。解决此问题的方法是创建一个自定义 .ashx 页面/处理程序来提供该文件。
该文件背后的代码应类似于以下内容:
public class Download : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
Response.ContentType = ""text/pdf"";
Response.AppendHeader("Content-Disposition","attachment; filename=File.pdf");
outputDoc.Save(Response.OutputStream, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3362 次 |
最近记录: |