how to save pdf on server map path using iTextsharp

26,225

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.

Share:
26,225
Admin
Author by

Admin

Updated on June 27, 2020

Comments

  • Admin
    Admin almost 4 years

    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?