在MVC 4中导出为pdf(以pdf格式嵌入HTML)

时间:2015-02-23 11:48:49

标签: asp.net-mvc-4 pdf itextsharp

我正在尝试使用MVC 4导出pdf。在尝试在pdf文档中嵌入Html时导出时出错:

  • 类型或命名空间名称'工具'在命名空间中不存在 ' iTextSharp的'

我添加了iTextSharp.dll,但我不知道为什么我会收到错误。请提前帮助我。

下面是我的方法:

  public FileResult ExportData()
    {
        List<Tb_ModalListFileUpload> objlist = new List<Tb_ModalListFileUpload>();

        objlist = (from p in obj.Tb_ModalListFileUpload select p).ToList();

        WebGrid wd = new WebGrid(source: objlist, canPage: false, canSort: false);

        string griddata = wd.GetHtml(
        columns: wd.Columns
        (
        wd.Column(columnName: "SRNO", header: "SRNO"),
        wd.Column(columnName: "ModelName", header: "Model Name"),
        wd.Column(columnName: "ModelCC", header: "Model CC"),

        wd.Column(columnName: "ModelRate", header: "Model Rate"),
        wd.Column(columnName: "ModelRC", header: "Model RC"),
        wd.Column(columnName: "IncWith0", header: "Inc With 0"),
        wd.Column(columnName: "IncWith50", header: "Inc With 50"),
        wd.Column(columnName: "Provisional", header: "Provisional"),
        wd.Column(columnName: "NetPriceWith0", header: "Net Price With 0"),
        wd.Column(columnName: "NetPriceWith50", header: "Net Price With 50")

        )
        ).ToString();

        string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", griddata);
        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.Add(new Paragraph("Hello World!"));
            document.Close();
            output.Position = 0;
            return new FileStreamResult(output, "application/pdf");
        }

        }

2 个答案:

答案 0 :(得分:2)

除了iTextSharp的主要DLL之外,您还需要为HTML处理添加单独但相关的XMLWorker

答案 1 :(得分:0)

迟到的评论,但也许它可以帮助其他人。

该软件包不可用,请尝试单独下载。我使用了以下链接Download here

我遇到了同样的问题,并将其整理出来。记得在下载/解压缩后引用DLL。