之前有写过根据文件地址下载的例子,今天碰上没有文件地址,直接把文件内容存到数据库中的情况,同时需要提供下载功能,并且是pdf的;首先需要引用itextsharp.dll,里面有封装好的pdf类和字体类;直接上代码:
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"); }