ASP.Net MVC将WebGrid导出为PDF

时间:2017-12-05 10:17:53

标签: c# asp.net asp.net-mvc

我正在尝试将WebGrid导出到PDF,并且我的控制器中有以下代码:

public FileStreamResult CreatePdf()
{
    List<CertificationListViewModel> all = new List<CertificationListViewModel>();

    using (DBEntities db = new DBEntities())
    {
        all = db.Certifications.ToList();
    }

    WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);

    string gridHtml = grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Name", "Nome"),
            grid.Column("Classification", "Classificação"),
            grid.Column("Date", "Data de Realização") 
        )
    ).ToString();
    string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
    var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
    using (var input = new MemoryStream(bytes))
    {
        var output = new MemoryStream();
        var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;
        document.Open();

        var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
        xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
        document.Close();
        output.Position = 0;
        return new FileStreamResult(output, "application/pdf");
    }
}

代码在这一行中给我一个错误:

all = db.Certifications.ToList();

这是出现的错误:

  

无法隐式转换类型&#39; System.Collections.Generic.List&lt; HIQTraining.Model.Certification&gt;&#39;到&#39; System.Collections.Generic.List&lt; HIQTrainingSite.ViewModel.CertificationListViewModel&gt;&#39;

我不确定错误是什么,如果某人有一个我会欣赏的想法!

P.S:我在项目中导出了以下iTextSharp个库:

using iTextSharp.text;
using iTextSharp.text.pdf;

1 个答案:

答案 0 :(得分:0)

错误告诉您您的值属于不同类型。 (这是有道理的,我不希望&#34;查看&#34;模型存储在数据库中。)因此,您需要以某种方式从一个转换为另一个。

例如,如果您的视图模型可以使用对象初始值设定器简单构建,那么您可以在all = db.Certifications.ToList() .Select(c => new CertificationListViewModel { SomeProperty = c.SomeProperty, AnotherProperty = c.AnotherProperty }); 投影中构建它:

List<Certification> all = new List<Certification>();

如果有很多属性,像AutoMapper这样的库可以帮助解决这个问题。

相反,如果您实际上想要数据库模型列表,那么您需要更改变量的类型以匹配:

$data = 123456789