2012-07-19 30 views
0

我正在尝试的是在桌面上的一个屏幕上有一个按钮,当点击该按钮时,下载带有用户看到的表格内容的PDF。如何通过mvc动作发送html表格?

这是我如何创建PDF,什么动作方法看起来像......

public ActionResult DownloadPdf(string content) 
{ 
    MemoryStream outputStream = new MemoryStream(); 
    MemoryStream workStream = new MemoryStream(); 
    Document document = new Document(); 
    PdfWriter.GetInstance(document, workStream); 
    document.Open(); 
    document.Add(new Paragraph(content)); 
    document.Close(); 

    byte[] byteInfo = workStream.ToArray(); 
    outputStream.Write(byteInfo, 0, byteInfo.Length); 
    outputStream.Position = 0; 

    //Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf"); 
    //return File(byteInfo, "application/pdf", "test.pdf"); 
    return File(outputStream, "application/pdf", "test.pdf"); 
} 

这是表我尝试打印...

<table class="donationTable statementTable"> 
    <tr> 
    <th>Month</th> <th>Fees</th> 
    </tr> 
    <tr> 
    <td> 
     Jan 
    </td> 
    <td> 
     $5 
    </td> 
    </tr>  
</table> 

<a href = "@Url.Action("DownloadPdf", "Home", new { content = "" })">Download</a> 
+0

该表格是如何生成的?你正在使用一些服务器端控制?你打算使用什么库来创建一个PDF文件,因为我们都知道.NET没有内置的这种能力。 – 2012-07-19 08:31:38

+0

表格是硬编码(这是您向我们展示的内容)还是包含动态数据?此外,我已将'itextsharp'标记添加到您的问题中,显然这是您用于生成PDF的框架。 – 2012-07-19 08:33:30

+0

几个PDF生成器库可以从URL创建PDF。 – 2012-07-19 08:33:54

回答

0

您可能需要请看following article on CodeProject,它说明了使用iTextsharp将Razor视图转换为PDF的一个好方法。我们的想法是,你会把这个表到部分,然后:

public ActionResult DownloadPdf() 
{ 
    MyViewModel model = ... 
    return this.ViewPdf("My table", "_SomePartial", model); 
} 

ViewPdf是执行Razor视图和在一个字符串,然后将其馈送到iTextSharp的,并转换成PDF检索其呈现的输出的扩展方法。

现在你可以有你的页面指向这个动作锚,这将允许次用户下载PDF:

@Html.ActionLink("Export table as Pdf", "DownloadPdf", null, new { target = "_blank" }) 

这是说,你应该知道,iTextSharp的还没有被设计为转换HTML转换成PDF格式,并对其提供非常有限的支持。如果你的HTML表格中有一些奇特的CSS规则,它们将不会被翻译。

+0

如何使用viewpdf? – Beginner 2012-07-19 11:21:14

+0

正如我的回答所示:'返回this.ViewPdf(“我的表”,“_SomePartial”,模型);'。但是你必须从'PdfViewController'派生而不是'Controller',因为在那里定义了'ViewPdf'方法。只需从CodeProject文章下载示例项目,即可开始播放。 – 2012-07-19 11:26:06