将HTML转换为pdf并将其保存到给定位置,而无需打开"另存为"或"下载"窗口

时间:2015-07-15 09:23:16

标签: c# asp.net pdf-generation

我正在将html转换为pdf。它工作正常。但是当我尝试将html保存到任何位置时,它会给我错误Network path not found。 我有一些代码

  #region Trying to convert pdf

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        StringReader sr = new StringReader(htmlStringToConvert);
        iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 100f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
        #endregion

我在htmlparser.Parse(sr)收到错误。

提前致谢

1 个答案:

答案 0 :(得分:0)

Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");

        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);
        DivMaster.RenderControl(hw);

        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 20, 20, 10, 20);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);


        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();

在设计页面中添加DivMaster(div)并在DivMaster中添加您的HTML代码。 注意:在整个HTML设计中使用%px