将c#表格转换为PDF文件

本文关键字:PDF 文件 转换 表格 | 更新日期: 2023-09-27 18:09:08

我试图把我的表(System.Web.UI.WebControls)使用StringWriter &htmltextwwriter,但我得到一个错误的pdf文件。

下面是我的代码:
        table.RenderControl(htw);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Reception.pdf");
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //render the htmlwriter into the response  
        HttpContext.Current.Response.Write(headerTable);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();

打开pdf文件时出现"error in loading document pdf"

将c#表格转换为PDF文件

iTextSharp类与此相关。我把代码改成这样:

        table.RenderControl(htw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Reception.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();