简体   繁体   中英

Convert Div Content to PDF and save on server path

I want to convert Div content into pdf and save that created pdf file on server path without asking to me save file (download file).

I converted pdf file and aslo saved that file in server path.

But In my code it also shows file download option which I want to remove.

I don't want to give pdf file save as option because I saved created file in server path.

Below is My code:

        string appPath = HttpContext.Current.Request.ApplicationPath;
        string path = Server.MapPath(appPath + "/Attachment/Test.pdf");
        if (File.Exists(path))
            File.Delete(path);
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        createDiv.RenderControl(hw);
        var output = new FileStream(path, FileMode.Create);
        StringReader sr = new StringReader(sw.ToString());
        iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 100f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, output);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.End();

Thanks, Hitesh

The reason the save dialog is showing is because you are writing to the response. If you only want to save to the local disk, simply remove all references to response. You can then do a Response.Redirect(...) or similar to point the user to the next page.

Using MemoryStream

If you intend to write the PDF to a database you should use a MemoryStream (see MSDN) instead of a FileStream . You can then call the MemoryStream.ToArray() method which will return a byte array you can store in the database.

Assuming you are using Entity Framework:

var output = new MemoryStream();
//snip
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, output);
//snip
myEntityFrameworkObject.Data = output.ToArray();
DataContext.SaveChanges();

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