mvc 將展現內容以Pdf格式下載下來

以前有寫過根據文件地址下載的例子,今天碰上沒有文件地址,直接把文件內容存到數據庫中的狀況,同時須要提供下載功能,而且是pdf的;首先須要引用itextsharp.dll,裏面有封裝好的pdf類和字體類;直接上代碼:html

 

  private static readonly string 標楷體Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
   "KAIU.TTF");//標楷體

 

 public ActionResult met_word_automation(string al_id)
        {
            ClassicCaseService.zkdz_classic_case _zkdz_classic_case = ws.IGetModel(al_id);
           string htmlText = "<div style='text-align:center;'><h2>" + _zkdz_classic_case.Title + "</h2></div>";
            htmlText += "<div style='float:right'>" + _zkdz_classic_case.CaseNo + "</div>";
            htmlText += _zkdz_classic_case.Content;

            if (string.IsNullOrEmpty(htmlText))
            {
                return null;
            }
            //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,因此一概加上<p>標籤
            htmlText = "<p>" + htmlText + "</p>";

            MemoryStream outputStream = new MemoryStream();//要把PDF寫到哪一個串流
            byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串轉成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Document doc = new Document();//要寫PDF的文件,建構子沒填的話預設直式A4
            PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
            //指定文件預設開檔時的縮放爲100%
            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            //水印字體
            BaseFont bf = BaseFont.CreateFont(標楷體Path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            //生成水印
            writer.PageEvent = new PdfEventHanler("真快電子送達科技服務有限公司", bf);//_zkdz_classic_case.TrialCourt  譚亮修改成公司名
            //開啓Document文件 
            doc.Open();
            //使用XMLWorkerHelper把Html parse到PDF檔裏
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
            //將pdfDest設定的資料寫到PDF檔
            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();
            return File(outputStream.ToArray(), "application/pdf", _zkdz_classic_case.CaseNo + ".pdf");

        }
相關文章
相關標籤/搜索