2011-05-19 38 views
0

我的项目与NerdDinner非常相似,我使用PdfSharp生成pdf文档。阻止ActionResult发布到新页面?

我认为我使用这个:

<%: 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文件直接显示。

回答

4

要返回FileResult而不是ActionResult。另外,我会将它保存到MemoryStream并返回字节数组,而不是使用文件。以下完整解决方案

public FileResult 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); 


    MemoryStream stream = new MemoryStream(); 
    document.Save(stream, false); 

    return File(stream.ToArray(), "application/pdf"); 
} 
+1

我想知道为什么你建议**另外,我会将它保存到一个MemoryStream并返回字节数组,而不是使用文件**。 – DanielB 2011-05-19 13:16:57

+0

因为如果将其保存到文件中,它可能与另一个请求具有相同的名称,并且您可能会获得另一个用户的文件。如果您要使用文件,则需要为请求唯一命名。 – 2011-05-19 13:19:45

+0

好吧,我错过了'document.Save(filename)'静态文件名。这确实非常重要。 Thx开启我的眼睛!这值得+1 ;-) – DanielB 2011-05-19 13:22:56

2

就应该更换这些线路:

Process.Start(filename); 
return View(); 

return File(filename, "application/pdf"); 

您还可能有第三PARAM与下载的文件名,如果它应该是操作名称不同。

return File(filename, "application/pdf", "myGeneratedPdf.pdf"); 

还可以肯定的文件名是每个请求的唯一或使用MemoryStream就像是由克里斯·Kooken建议。

Btw:Process.Start(filename)将在服务器机器上运行该文件。这可能会在您的开发机器上工作,但在现场服务器上,pdf将在服务器上打开!

+0

''文件'没有超载方法需要1个参数' – Niklas 2011-05-19 13:11:09

+0

是的,我错过了内容类型。纠正了几秒钟前。 – DanielB 2011-05-19 13:12:10

+0

+1在服务器上打开的pdf将在服务器上打开, – Niklas 2011-05-19 13:38:32