5

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?

  • possible duplicate of [Save the generated pdf directly to the server directory folder without user prompt](http://stackoverflow.com/questions/4253989/save-the-generated-pdf-directly-to-the-server-directory-folder-without-user-prom) – Bruno Lowagie Jun 26 '15 at 17:14

1 Answers1

10

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.

kaveman
  • 4,339
  • 25
  • 44
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • This shows error - PdfWriter.GetInstance(pdfDoc, New FileStream(path); it shows error on `New Filestream`. –  Jun 26 '15 at 17:15
  • 1
    yes i solved already with this code : `PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));` –  Jun 26 '15 at 17:17
  • Accepted :-) Thank you :-) –  Jun 26 '15 at 17:20
  • @Bruno Lowagie do you how to do it using `XMLWorkerHelper` – chethu Feb 10 '20 at 09:03