how to save pdf on server map path using iTextsharp

蓝咒 提交于 2020-01-11 06:17:07

问题


i am using following code for generate pdf and it is work perfect:

  string strQuery = "select * from userdata";
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);

        //Create a dummy GridView
        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt;
        GridView1.DataBind();

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);

        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();

        htmlparser.Parse(sr);
        pdfDoc.Close();

        Response.Write(pdfDoc);
        Response.End();  

it works good. but i am able to save this pdf to on server map path.

i have written below after pdfDoc.Close();

   String path  = Server.MapPath("~/mypdf.pdf");

But it is not saving pdf to server map path.

how can i do this?


回答1:


You are currently writing the document to the following output stream: Response.OutputStream

Once you do pdfDoc.Close();, the PDF bytes are gone.

If you want to save the PDF to the server, then you need to replace the following line:

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

With this line:

PdfWriter.GetInstance(pdfDoc, new FileStream(context.Server.MapPath("~") + "mypdf.pdf");

Now your bytes won't be sent to the browser, but the PDF will be created on your server.



来源:https://stackoverflow.com/questions/31078442/how-to-save-pdf-on-server-map-path-using-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!