阻止 ActionResult 发布到新页面?
我的项目与 NerdDinner 非常相似,我正在使用 PdfSharp 生成 pdf 文档。
在我看来,我正在使用这个:
<%: Html.ActionLink("Pdf", "GeneratePdf1", "Persons")%>
调用这个 ActionResult:
public ActionResult GeneratePdf1()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document...
const string filename = "HelloWorld.pdf";
document.Save(filename);
Process.Start(filename);
return View();
}
对此的一些疑问/问题:
- 我不想发布链接。当您单击链接时,它应该只打开文件,但我不知道要返回什么以防止其发布。
- 我还希望出现“保存/打开”对话框。现在直接显示pdf文件。
My project is very similar to NerdDinner and I'm generating a pdf-document using PdfSharp.
In my view I'm using this:
<%: Html.ActionLink("Pdf", "GeneratePdf1", "Persons")%>
Calling this ActionResult:
public ActionResult GeneratePdf1()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document...
const string filename = "HelloWorld.pdf";
document.Save(filename);
Process.Start(filename);
return View();
}
A few questions/problems on this:
- I don't want the link to post. When you click the link it should just open the file, but I don't know what to return to prevent it from posting.
- I'd also like the "save/open" dialog to appear. Right now the pdf file is displayed directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要返回
FileResult
而不是ActionResult
。另外,我会将其保存到 MemoryStream 并返回字节数组,而不是使用文件。完整解决方案如下。You want to return a
FileResult
not anActionResult
. Also, I would save it to aMemoryStream
and return the byte array, not use a file. Full solution below.您应该替换这些行:
with
您还可以有第三个参数,其中包含下载的文件名(如果它与操作名称不同)。
还要确保每个请求的文件名是唯一的,或者使用
MemoryStream
就像 Chris Kooken 建议的那样。顺便说一句:
Process.Start(filename)
将在服务器计算机上运行该文件。这可能在您的开发机器上工作,但在实时服务器上,pdf 将在服务器上打开!you should replace these lines:
with
You may also have a third param with the downloaded filename, if it should be different to the action name.
Also be sure the filename is unique per request or use a
MemoryStream
like it is suggested by Chris Kooken.Btw:
Process.Start(filename)
will run the file on the server machine. that may work on your development machine, but on a live server the pdf will open on the server!!!