简体   繁体   English

将Div内容转换为PDF并保存在服务器路径上

[英]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). 我想将Div内容转换为pdf并将创建的pdf文件保存在服务器路径上,而无需询问我保存文件(下载文件)。

I converted pdf file and aslo saved that file in server path. 我转换了pdf文件,aslo将该文件保存在服务器路径中。

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. 我不想将pdf文件另存为选项,因为我将创建的文件保存在服务器路径中。

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 谢谢,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. 然后,您可以执行Response.Redirect(...)或类似操作以将用户指向下一页。

Using MemoryStream 使用MemoryStream

If you intend to write the PDF to a database you should use a MemoryStream (see MSDN) instead of a FileStream . 如果打算将PDF写入数据库,则应使用MemoryStream (请参见MSDN)而不是FileStream You can then call the MemoryStream.ToArray() method which will return a byte array you can store in the database. 然后,您可以调用MemoryStream.ToArray()方法,该方法将返回可以存储在数据库中的字节数组。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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