簡體   English   中英

將Div內容轉換為PDF並保存在服務器路徑上

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM