直接上代码
- html
- <div id="div_workInfo">
- /// 这里放想要导出的 html 元素
- </div>
- <form action="@Url.Action("ExportWord")" method="post" id="formWord"> <input type="hidden" id="hidWord" name="hidWord" /></form>
- function ExportWord() {
- var html = $("#div_workInfo").html();
- $("#hidWord").val(encodeURIComponent(html));
- $("#formWord").submit();
- } ///from 表单方式提交这段 html
接下来就是后台接收了
- [HttpPost]
- public ActionResult ExportWord(FormCollection form)
- {
- string html = Server.UrlDecode(form["hidWord"]);/// 接收前台的 html 的
- byte[] pdfFile = this.ConvertHtmlTextToPDF(html);///pdf 执行这个就可以了
- /// 这里执行 word 操作
- sb.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\"xmlns:o=\"urn:schemas-microsoft-com:office:office\"xmlns:w=\"urn:schemas-microsoft-com:office:word\"xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns=\"http://www.w3.org/TR/REC-html40\">");
- sb.Append("<head><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->");
- sb.Append("<style>@page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;}@page Section1{size:841.9pt 595.3pt; mso-page-orientation:landscape; margin:89.85pt 72.0pt 89.85pt 72.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;}div.Section1 {page:Section1;}</style></head>");
- sb.Append("<body lang=ZH-CN style='tab-interval:21.0pt'>");
- sb.Append("<div class='Section1'style='font-family: 宋体;'>");
- sb.Append(html);
- sb.Append("</div> </body>");
- sb.Append("</html>"); 说明一下 加了 style 可以设置页面方式为横向 加 html 那边 可以设置 web 视图为 页面视图
- return File(pdfFile, "application/pdf", ""+" 报销表_"+ DateTime.Now.ToString("yyyyMMddhhmmss") +".pdf");
- }
- 这里用到了 iTextSharp 直接可以直接在项目 nuget 里面下载安装
- /// <summary>
- /// 将 Html 文字 输出到 PDF 档里
- /// </summary>
- /// <param name="htmlText"></param>
- /// <returns></returns>
- public byte[] ConvertHtmlTextToPDF(string htmlText)
- {
- 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);
- // 开启 Document 文件
- doc.Open();
- // 使用 XMLWorkerHelper 把 Html parse 到 PDF 档里
- XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new Models.UnicodeFontFactory());//UnicodeFontFactory 这个类是防止中午问题的 我在下面贴一下 直接复制过去就 OK 了
- // 将 pdfDest 设定的资料写到 PDF 档
- PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
- writer.SetOpenAction(action);
- doc.Close();
- msInput.Close();
- outputStream.Close();
- // 回传 PDF 档案
- return outputStream.ToArray();
- }
- UnicodeFontFactory 类 的内容 继承 FontFactoryImp 类
- public class UnicodeFontFactory : FontFactoryImp
- {
- private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
- "arialuni.ttf");//arial unicode MS 是完整的 unicode 字型.
- private static readonly string 标楷体 Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
- "KAIU.TTF");// 标楷体
- public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
- bool cached)
- {
- // 可用 Arial 或标楷体, 自己选一个
- BaseFont baseFont = BaseFont.CreateFont(标楷体 Path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- return new Font(baseFont, size, style, color);
- }
- }
- /// 导出的 pdf 这个是百度上看到的自己抄了一下 发表主要是为了自己收集下来 发表的内容这里都有用过是有效果的
来源: https://www.cnblogs.com/manwwx129/p/9222799.html