How to save pdf to server map path using iTextsharp
I am using the following code to generate pdf and it works great:
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 well. but i can save this pdf on the server map path.
I wrote below after pdfDoc.Close ();
String path = Server.MapPath("~/mypdf.pdf");
But this is not saving the PDF file on the path to the server map.
How can i do this?
+3
source to share
1 answer
The document is currently being written to the following output stream: Response.OutputStream
Once you do pdfDoc.Close();
, the PDF bytes are gone.
If you want to save the PDF file to the server, 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 will not be sent to the browser, but the PDF will be generated on your server.
+5
source to share