[英]Convert Div Content to PDF and save on server path
我想将Div内容转换为pdf并将创建的pdf文件保存在服务器路径上,而无需询问我保存文件(下载文件)。
我转换了pdf文件,aslo将该文件保存在服务器路径中。
但是在我的代码中,它还显示了我要删除的文件下载选项。
我不想将pdf文件另存为选项,因为我将创建的文件保存在服务器路径中。
下面是我的代码:
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();
谢谢,Hitesh
显示保存对话框的原因是因为您正在写入响应。 如果只想保存到本地磁盘,只需删除所有对响应的引用。 然后,您可以执行Response.Redirect(...)
或类似操作以将用户指向下一页。
使用MemoryStream
如果打算将PDF写入数据库,则应使用MemoryStream
(请参见MSDN)而不是FileStream
。 然后,您可以调用MemoryStream.ToArray()
方法,该方法将返回可以存储在数据库中的字节数组。
假设您正在使用实体框架:
var output = new MemoryStream();
//snip
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, output);
//snip
myEntityFrameworkObject.Data = output.ToArray();
DataContext.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.