zoukankan      html  css  js  c++  java
  • Asp.net mvc word预览与打印

    解决方案:

    1. 在后台把word文件转化成pdf,在前台用iframe显示pdf,打印iframe,即可。

    优点:用户体验好。

    缺点:不支持IE。

    实现 :

    引用netoffice组件

    主要代码:

    Word.Application wordApplication = new Word.Application();
                    Word.Document pDoc = wordApplication.Documents.Open(path);
                    pDoc.Activate();
    
                    pDoc.SaveAs(pdf, WdSaveFormat.wdFormatPDF);
                    wordApplication.Quit();
                    wordApplication.Dispose();

    2. 在后台把word转化面html,读取html文本,增加打印脚本,输出到前台。

    优点:浏览器支持的好。

    缺点:用html显示word,不是太好看。

    实现 :

    引用:

    主要代码:

        public class WordToHtmlConverter
        {
            /// <summary>
            /// Convert Docx to Html
            /// </summary>
            /// <param name="source">source file full name</param>
            /// <returns>htmlstring</returns>
            public static string ToHtml(string source)
            {
                var htmlString = string.Empty;
                var file = new FileInfo(source);
    
                byte[] bytes = File.ReadAllBytes(file.FullName);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    memoryStream.Write(bytes, 0, bytes.Length);
                    using (var wDoc = WordprocessingDocument.Open(memoryStream, true))
                    {
                        var imageFolder = source.Substring(0, source.Length - 5) + "_files";
                        int imageCounter = 0;
                        
                        HtmlConverterSettings settings = new HtmlConverterSettings()
                        {
                            AdditionalCss = "body { margin: 1cm auto; max- 20cm; padding: 0; }",
                            PageTitle = "新系统",
                            FabricateCssClasses = true,
                            CssClassPrefix = "pt-",
                            RestrictToSupportedLanguages = false,
                            RestrictToSupportedNumberingFormats = false,
                            ImageHandler = imageInfo =>
                            {
                                DirectoryInfo localDirInfo = new DirectoryInfo(imageFolder);
                                if (!localDirInfo.Exists)
                                    localDirInfo.Create();
                                ++imageCounter;
                                string extension = imageInfo.ContentType.Split('/')[1].ToLower();
                                ImageFormat imageFormat = null;
                                if (extension == "png")
                                    imageFormat = ImageFormat.Png;
                                else if (extension == "gif")
                                    imageFormat = ImageFormat.Gif;
                                else if (extension == "bmp")
                                    imageFormat = ImageFormat.Bmp;
                                else if (extension == "jpeg")
                                    imageFormat = ImageFormat.Jpeg;
                                else if (extension == "tiff")
                                {
                                    // Convert tiff to gif.
                                    extension = "gif";
                                    imageFormat = ImageFormat.Gif;
                                }
                                else if (extension == "x-wmf")
                                {
                                    extension = "wmf";
                                    imageFormat = ImageFormat.Wmf;
                                }
    
                                // If the image format isn't one that we expect, ignore it,
                                // and don't return markup for the link.
                                if (imageFormat == null)
                                    return null;
    
                                string imageFileName = imageFolder + "/image" +
                                    imageCounter.ToString() + "." + extension;
                                try
                                {
                                    imageInfo.Bitmap.Save(imageFileName, imageFormat);
                                }
                                catch (System.Runtime.InteropServices.ExternalException)
                                {
                                    return null;
                                }
                                string imageSource = localDirInfo.Name + "/image" +
                                    imageCounter.ToString() + "." + extension;
    
                                XElement img = new XElement(Xhtml.img,
                                    new XAttribute(NoNamespace.src, imageSource),
                                    imageInfo.ImgStyleAttribute,
                                    imageInfo.AltText != null ?
                                        new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                                return img;
                            }
                        };
                        XElement htmlElement = HtmlConverter.ConvertToHtml(wDoc, settings);
    
                        // Produce HTML document with <!DOCTYPE html > declaration to tell the browser we are using HTML5.
                        var html = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
    
                        htmlString = html.ToString(SaveOptions.DisableFormatting);
                    }
                }
    
                return htmlString;
            }
        }
            public string NoticePrint(NoticeResult model)
            {
                // 第一步,生成新的doc文档,替换模板文件中的标签,这里用的是NPOI,这个方法就不显示了,没什么东西。
                var path = this.GetDocFileName(model);
    
                // 第二步,把doc文件,转化成html文件
                var html = WordToHtmlConverter.ToHtml(path);
    
                // 第三步,对html追加script脚本
                var result = html + GetPrintScript();
    
                // 第四步,返回
                return result;
            }
    
            private string GetPrintScript()
            {
                return  @"<script type='text/javascript'> window.onload = function() { window.print(); };</script >";
            }

    Controller Code:

    public ActionResult Print(NoticeResult model)
            {
                var result = new Response<bool>();
    
                if (model != null)
                {
                    var html = this.service.NoticePrint(model);
                    
                    return Content(html, "text/html");
                }
    
                result.ErrMsg = "打印参数异常";
    
                return Json(result);
    
            }

    代码有删减,不能拿来直接用!!!

  • 相关阅读:
    c#使用SoundPlayer播放wav格式音频
    c#NAudio 录音功能实现
    c#异步方法调用
    c# 读取文件目录下的信息
    angular笔记_1
    js获取form元素,不使用id
    事物回滚机制
    ckplayer跨域调用
    帝国移动pc站文章
    页面切换导航样式也随之改变
  • 原文地址:https://www.cnblogs.com/hankuikui/p/8692399.html
Copyright © 2011-2022 走看看