Save the generated pdf directly to the server directory folder without user prompt

旧城冷巷雨未停 提交于 2019-12-12 18:19:20

问题


A friend of mine gave me this task so I can learn advance programming a little bit easier. I am currently doing convertion of an html page to pdf using itext sharp and email the pdf as an attachement. My idea is to save the pdf first to the server machine in the folder name ToBeEmailedPDF folder before using it as an email attachment. The thing that bothers me is that this dialog as what you can see in the picture shows up using the code that I have below.

StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
pnlPDF.RenderControl(hw); // pnlPDF contains the html contents to be converted to pdf
string htmlDisplayText = sb.ToString();
Document document = new Document();
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
StringReader se = new StringReader(htmlDisplayText);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
// step 5: we close the document
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();

I know many of you out there knows a better way or know how to solve my problem. Please help me. Thank you!


回答1:


There is big difference between client-side and server-side.

Response class can output contents to client machine, if you need to save file on server use something like File.WriteAllBytes (msdn) method




回答2:


What you are trying to achieve is impossible for security reasons. Only the user can decide where he wants the attachment to be saved. Imagine if this was possible: you would then be able to save any kind of viruses into any kind of folders on the user's computer. As an alternative to showing the Save dialog you could open the PDF inline:

Response.AddHeader("Content-Disposition", "inline; filename=report.pdf");



回答3:


You can save it using the following code:

PdfWriter.GetInstance(pdfDoc, new FileStream(context.Server.MapPath("~") + "/PDF/" + reportName + ".pdf", FileMode.Create));


来源:https://stackoverflow.com/questions/4253989/save-the-generated-pdf-directly-to-the-server-directory-folder-without-user-prom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!