简体   繁体   中英

how to save pdf on server map path using iTextsharp

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM