码迷,mamicode.com
首页 > Web开发 > 详细

net 预览文件 转换文件

时间:2018-11-15 18:37:53      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:var   +=   display   pac   hmm   监听   portal   sleep   bug   

预览SWF文件

 swfobject.js  (google浏览器 会阻止 需设置)

技术分享图片
@{
    ViewBag.Title = "PdfPreview";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var fileType = ViewBag.fileType;
    var swfpath = ViewBag.filePath;
}

<script src="~/Content/js/jquery.uploadify/swfobject.js"></script>
<script src="~/Content/js/jquery.uploadify/flexpaper_flash_debug.js"></script>

<script src="/Content/js/jquery.uploadify/jquery-1.4.1.min.js"></script>
<div id="app">
    <div id="contentText" style="border: dashed 1px #dddddd; background-color: white;">
        <div id="flashContent">
        </div>
    </div>
</div>

<script type="text/javascript">
    var swfVersionStr = "10.0.0";
    var swf = "@swfpath";
    //var swf = "http://localhost:8080/tmp/94D1390E-930D-4D41-BD88-72FDC3273755/94D1390E-930D-4D41-BD88-72FDC3273755.pdf";
    //var swf = "C:/Users/zz/Desktop/File/1.pdf";
    if (swf != "") {
        var swfpath = swf.replace(docx, swf).replace(xlsx, swf).replace(xls, swf).replace(doc, swf).replace("pdf", "swf");
        var xiSwfUrlStr = "playerProductInstall.swf";
        var swfFile = swfpath;

        var flashvars = {
            SwfFile: escape(swfFile),//编码设置  
            Scale: 0.6,
            ZoomTransition: "easeOut",//变焦过渡  
            ZoomTime: 0.5,
            ZoomInterval: 0.2,//缩放滑块-移动的缩放基础[工具栏]  
            FitPageOnLoad: true,//自适应页面  
            FitWidthOnLoad: true,//自适应宽度  
            PrintEnabled: true,//是否启用打印
            FullScreenAsMaxWindow: false,//全屏按钮-新页面全屏[工具栏]  
            ProgressiveLoading: true,//分割加载 
            //MinZoomSize: 0.2,//最小缩放  
            //MaxZoomSize: 3,//最大缩放 
            PrintToolsVisible: true,//是否显示打印工具
            ViewModeToolsVisible: true,//显示模式工具栏是否显示  
            ZoomToolsVisible: true,//缩放工具栏是否显示  
            FullScreenVisible: true,//是否全屏
            NavToolsVisible: true,//跳页工具栏  
            CursorToolsVisible: true,
            SearchMatchAll: true,//搜索匹配全部
            SearchToolsVisible: true,//是否显示搜索工具
            localeChain: "zh_CN"//语言
        };

        var params = {
        }

        params.quality = "high";
        params.bgcolor = "#ffffff";
        params.allowscriptaccess = "sameDomain";
        params.allowfullscreen = "true";
        var attributes = {};
        attributes.id = "FlexPaperViewer";
        attributes.name = "FlexPaperViewer";
        swfobject.embedSWF(
            "/Content/js/jquery.uploadify/FlexPaperViewer.swf",//默认显示的swfUrl
            "flashContent",//展示区域Id
            "100%",//展示宽度
            (window.innerHeight - 25) + "px",//战术高度
            swfVersionStr, xiSwfUrlStr,
            flashvars, params, attributes);
        swfobject.createCSS("#flashContent",//展示区域Id
            "display:block;text-align:center;");


        //滚动条监听
        window.onload = function () {
            if (window.addEventListener) {
                window.addEventListener(DOMMouseScroll, deltaDispatcher, false);
            }
            document.body.onmousewheel = deltaDispatcher;
        }
        function deltaDispatcher(event) {
            event = window.event || event;
            var delta = 0;
            if (event.wheelDelta) {
                delta = event.wheelDelta / 120;
                if (window.opera) {
                    delta = -delta;
                }
            } else if (event.detail) {
                delta = -event.detail;
            }
            if (event.preventDefault) {
                event.preventDefault();
            }
            var obj = swfobject.getObjectById("FlexPaperViewer");
            if (typeof (obj.externalMouseEvent) == function) {
                obj.externalMouseEvent(delta);
            }
        }
    }
</script>
View Code

预览音频 视频 图片

技术分享图片
@{
    ViewBag.Title = "文件预览";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var fileType = ViewBag.fileType;
    var filePath = ViewBag.filePath;
}

<div id="app">
    <el-container id="filePreview">
        @*(因为可能不支持vue动态绑定,所以改成js动态加载)*@

        @*<audio v-bind:style="{ ‘display‘:preview.audioShow}" controls>
                <source :src="preview.audioUrl" type="audio/mpeg">
                <source :src="preview.audioUrl" type="audio/ogg">
                <embed height="50" width="100" :src="preview.audioUrl">
            </audio>*@@*//音频*@

        @*<video  v-bind:style="{ ‘height‘: mainHeight - 17 + ‘px‘,‘width‘:‘100%‘,‘display‘:preview.videoShow}" controls autoplay>
                <source :src="preview.videoUrl" type="video/ogg">
                <source :src="preview.videoUrl" type="video/mp4">
                <source :src="preview.videoUrl" type="video/webm">
                <object :data="preview.videoUrl"  v-bind:style="{ ‘height‘: mainHeight - 17 + ‘px‘,‘width‘:‘100%‘}">
                    <embed  v-bind:style="{ ‘height‘: mainHeight - 17 + ‘px‘,‘width‘:‘100%‘}" :src="preview.videoUrl">
                </object>
            </video>*@@*//视频*@

        @*<img :src="preview.imgUrl" :style="{ ‘display‘:preview.imgShow}" />*@@*//图片*@
    </el-container>
</div>

<script>
    var app = new Vue({
        el: "#app",
        data: {
            mainHeight: window.innerHeight,
            preview: {
                fileUrl: "",
                audioUrl: "",
                videoUrl: "",
                imgUrl: "",
                fileShow: "none",
                audioShow: "none",
                videoShow: "",
                imgShow: "none"
            },
        },
        mounted: function () {
            const cur = this;
            window.onload = () => {
                cur.pageLoad();
            };
            window.onresize = () => {
                cur.mainHeight = window.innerHeight;
            }
        },
        methods: {
            pageLoad() {
                const cur = this;
                let fileType = "@fileType";//文件类型
                let filePath = "@filePath";//预览URL
                cur.preview = {
                    audioUrl: "",
                    videoUrl: "",
                    imgUrl: "",
                    audioShow: "none",
                    videoShow: "none",
                    imgShow: "none"
                };
                var filePreview = document.getElementById("filePreview");
                var str = "";
                switch (fileType) {

                    case "1"://视频
                        //cur.preview = {
                        //    audioUrl: "",
                        //    videoUrl: filePath,
                        //    imgUrl: "",
                        //    audioShow: "none",
                        //    videoShow: "",
                        //    imgShow: "none"
                        //};
                        str = "<video style=‘width:100%; height:" + (cur.mainHeight - 17) + "px;‘ controls autoplay>";
                        str += "< source src = ‘" + filePath + "‘ type = ‘video/ogg‘ >";
                        str += "<source src=‘" + filePath + "‘ type=‘video/mp4‘>";
                        str += "<source src=‘" + filePath + "‘ type=‘video/webm‘>";
                        str += "<object data=‘" + filePath + "‘ style=‘width:100%; height:" + (cur.mainHeight - 17) + "px;‘>";
                        str += "<embed style=‘width:100%; height:" + (cur.mainHeight - 17) + "px;‘ src=‘" + filePath + "‘>";
                        str += "</object></video>";
                        break;
                    case "2-1"://图片
                    case "2"://图片
                        //cur.preview = {
                        //    audioUrl: "",
                        //    videoUrl: "",
                        //    imgUrl: filePath,
                        //    audioShow: "none",
                        //    videoShow: "none",
                        //    imgShow: ""
                        //};
                        str = "<img src=\"" + filePath + "\"  />";
                        break;
                    case "3"://音频
                        //cur.preview = {
                        //    audioUrl: filePath,
                        //    videoUrl: "",
                        //    imgUrl: "",
                        //    audioShow: "",
                        //    videoShow: "none",
                        //    imgShow: "none"
                        //};
                        str = "<audio  controls=‘controls‘>";
                        str += "<source src = ‘" + filePath + "‘ type = ‘audio/mpeg‘ >";
                        str += "<source src=‘" + filePath + "‘ type=‘audio/ogg‘>";
                        str += "<object height=‘50‘ width=‘100‘ data=‘" + filePath + "‘>";
                        str += "<embed height=‘50‘ width=‘100‘ src=‘" + filePath + "‘>";
                        str += "</object></audio>";
                        break;
                    default:
                        break;
                }
                filePreview.innerHTML = str;
            },
        }
    });
</script>
View Code

 

后端:

1.返回定义好的文件类型

技术分享图片
private string[] imgExts = new string[] { ".BMP", ".GIF", ".JPEG", ".JPG", ".PNG", ".TIFF", ".TIF" };

//转换文件类型
result.Data.RelativePaths = (HttpContext.Current.Request.Url.Authority + "\\" + Index(result.Data.RelativePaths)).Replace("\\", "/");
                string fileext = Util.GetFileExt(doc.DocName).ToLower();
                if (imgExts.Contains(fileext.ToUpper()))//图片
                {
                    if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
                    {
                        result.Data.DocType = "2-2";//图片-swf
                    }
                    else
                    {
                        result.Data.DocType = "2-1";//图片
                    }
                }
                else if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(fileext))//音频
                {
                    result.Data.DocType = "3";
                }
                else if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(fileext))//视频
                {
                    result.Data.DocType = "1";
                }
                else if (".doc;.docx".Contains(fileext))//word
                {
                    if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html")
                    {
                        result.Data.DocType = "4-1";//word-html
                    }
                    else
                    {
                        result.Data.DocType = "4-2";//word-swf
                    }

                }
                else if (".xls;.xlsx".Contains(fileext))//excel
                {
                    if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html")
                    {
                        result.Data.DocType = "5-1";//excel-html
                    }
                    else
                    {
                        result.Data.DocType = "5-2";//excel-swf
                    }
                }
                else if (".txt".Contains(fileext))//文本
                {
                    if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
                    {
                        result.Data.DocType = "6-2";
                    }
                    else
                    {
                        result.Data.DocType = "6-1";
                    }
                }
                else if (".html;.htm".Contains(fileext))//网页
                {
                    if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
                    {
                        result.Data.DocType = "7-2";//网页-swf
                    }
                    else
                    {
                        result.Data.DocType = "7-1";//网页
                    }
                }
                else if (".pdf;.swf".Contains(fileext))//pdf
                {
                    result.Data.DocType = "8";
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                result.ErrCode = 1;
                result.ResultMsg = "获取文件失败!";
            }
            return result;
View Code

2.转换文件

技术分享图片
        /// <summary>
        /// 返回本地文件或共享文件
        /// </summary>
        /// <param name="path">相对路径</param>
        /// <param name="serverPath">共享服务器</param>
        /// <returns></returns>
        public string MapPath(string path, string serverPath = "")
        {
            string ph = path;
            if (string.IsNullOrWhiteSpace(path)) return "";
            string url = ConfigHelper.GetValue("ShareFileUrl");

            if (!string.IsNullOrEmpty(serverPath))
            {
                url = serverPath;
            }

            //共享文件夹能够连接
            if (ConnectShareFileSys())
            {
                ph = path.Replace("~", url).Replace("/", "\\");
            }
            else
            {
                ph = HttpContext.Current.Server.MapPath(path);
            }

            return ph;
        }


        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                return "127.0.0.1";
            }
            return result;
        }

        #region Index页面
        /// <summary>
        /// Index页面
        /// </summary>
        /// <param name="url">例:/uploads/......XXX.xls</param>
        public string Index(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return "";
            string physicalPath = AppDomain.CurrentDomain.BaseDirectory + url;
            string extension = Path.GetExtension(physicalPath);
            string htmlUrl = "";
            if (imgExts.Contains(extension.ToUpper()))//图片
            {
                htmlUrl = PreviewPicture(physicalPath, url);
                return htmlUrl;
            }
            if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(extension.ToLower()))//音频
            {
                htmlUrl = PreviewAudio(physicalPath, url);
                return htmlUrl;
            }
            if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(extension.ToLower()))//视频
            {
                htmlUrl = PreviewVideo(physicalPath, url);
                return htmlUrl;
            }
            switch (extension.ToLower())
            {
                case ".xls":
                case ".xlsx":
                    htmlUrl = PreviewExcel(physicalPath, url);
                    break;
                case ".doc":
                case ".docx":
                    htmlUrl = PreviewWord(physicalPath, url);
                    break;
                case ".txt":
                    htmlUrl = PreviewTxt(physicalPath, url);
                    break;
                case ".pdf":
                case ".swf":
                    htmlUrl = PreviewPdf(physicalPath, url);
                    break;
                case ".html":
                case ".htm":
                    htmlUrl = PreviewHtml(physicalPath, url);
                    break;
            }
            return htmlUrl;
        }
        #endregion
        #region 预览Excel
        /// <summary>
        /// 预览Excel
        /// </summary>
        /// <param name="physicalPath">绝对路径</param>
        /// <param name="url">相对路径</param>
        /// <returns></returns>
        public string PreviewExcel(string physicalPath, string url)
        {
            string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".pdf";
            if (!File.Exists(pdfPath))
            {
                if (ExcelToPdf(physicalPath, pdfPath))//转换成pdf
                {
                    //预览pdf
                    return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
                }
                else//转换成html
                {
                    return ExcelToHtml(physicalPath, url);
                }
            }
            else
            {
                //预览pdf
                return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
            }
        }
        /// <summary>
        /// 预览Excel转换成html(备用)
        /// </summary>
        /// <param name="physicalPath">绝对路径</param>
        /// <param name="url">相对路径</param>
        /// <returns></returns>
        public string ExcelToHtml(string physicalPath, string url)
        {
            Excel.Application application = null;
            Excel.Workbook workbook = null;
            application = new Excel.Application();
            object missing = Type.Missing;
            object trueObject = true;
            application.Visible = false;
            application.DisplayAlerts = false;
            workbook = application.Workbooks.Open(physicalPath, missing, trueObject, missing, missing, missing,
              missing, missing, missing, missing, missing, missing, missing, missing, missing);
            //Save Excel to Html
            object format = Excel.XlFileFormat.xlHtml;
            string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
            String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
            workbook.SaveAs(outputFile, format, missing, missing, missing,
                     missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,
                     missing, missing, missing, missing);
            workbook.Close();
            application.Quit();
            return Path.GetDirectoryName(url) + "\\" + htmlName;
        }
        /// <summary>
        /// 把Excel文件转换成PDF格式文件(office)
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public bool XLSConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Excel.ApplicationClass application = null;
            //Excel.Application application = null;//如不支持换上面注释代码
            Excel.Workbook workBook = null;
            try
            {
                application = new Excel.ApplicationClass();
                //application = new Excel.Application();//如不支持换上面注释代码
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

        /// <summary>
        /// 把Excel文件转换成PDF格式文件(Aspose)
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public bool ExcelToPdf(string sourcePath, string targetPath)
        {
            bool result = false;
            try
            {
                //Excel
                Workbook excel = new Workbook(sourcePath);
                excel.Save(targetPath, Aspose.Cells.SaveFormat.Pdf);
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        #endregion
        #region 预览Word
        /// <summary>
        /// 预览Word
        /// </summary>
        /// <param name="physicalPath">绝对路径</param>
        /// <param name="url">相对路径</param>
        /// <returns></returns>
        public string PreviewWord(string physicalPath, string url)
        {
            string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".pdf";
            if (!File.Exists(pdfPath))
            {
                if (WordToPdf(physicalPath, pdfPath))//转换成pdf
                {
                    //预览pdf
                    return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
                }
                else//转换成html
                {
                    return WordToHtml(physicalPath, url);
                }
            }
            else
            {
                //预览pdf
                return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
            }
        }
        /// <summary>
        /// 预览Word转换成html(备用)
        /// </summary>
        /// <param name="physicalPath">绝对路径</param>
        /// <param name="url">相对路径</param>
        /// <returns></returns>
        public string WordToHtml(string physicalPath, string url)
        {
            Word._Application application = null;
            Word._Document doc = null;
            application = new Word.Application();
            object missing = Type.Missing;
            object trueObject = true;
            application.Visible = false;
            application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,
              missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            //Save Excel to Html
            object format = Word.WdSaveFormat.wdFormatHTML;
            string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
            String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
            doc.SaveAs(outputFile, format, missing, missing, missing,
                     missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,
                     missing, missing, missing, missing);
            doc.Close();
            application.Quit();
            return Path.GetDirectoryName(url) + "\\" + htmlName;
        }
        //Word转换成pdf
        /// <summary>
        /// 把Word文件转换成为PDF格式文件(office)
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        private bool DOCConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;
            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            //Word.Application wordApplication = new Word.Application();//如不支持换上面注释代码
            Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;

                Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                wordDocument = wordApplication.Documents.Open(
                ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing);

                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                    paramExportFormat, paramOpenAfterExport,
                    paramExportOptimizeFor, paramExportRange, paramStartPage,
                    paramEndPage, paramExportItem, paramIncludeDocProps,
                    paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                    paramBitmapMissingFonts, paramUseISO19005_1,
                    ref paramMissing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

        /// <summary>
        /// 把Word文件转换成为PDF格式文件(Aspose)
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        private bool WordToPdf(string sourcePath, string targetPath)
        {
            bool result = false;
            try
            {
                Aspose.Words.Document doc = new Aspose.Words.Document(sourcePath);
                doc.Save(targetPath, Aspose.Words.SaveFormat.Pdf);
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        #endregion
        #region 预览Txt
        /// <summary>
        /// 预览Txt
        /// </summary>
        public string PreviewTxt(string physicalPath, string url)
        {
            string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".pdf";
            if (!File.Exists(pdfPath))//不存在pdf
            {
                if (TxtToPdf(physicalPath, pdfPath))//转换成功
                {
                    //预览pdf
                    return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
                }
                else
                {
                    return url;
                }
            }
            else
            {
                //预览pdf
                return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
            }
        }
        /// <summary>
        /// 把txt文件转换成pdf格式文件
        /// </summary>
        /// <param name="txtFile"></param>
        /// <param name="pdfFile"></param>
        /// <returns></returns>
        public bool TxtToPdf(string txtFile, string pdfFile)
        {
            bool result = false;
            try
            {
                //第一个参数是txt文件物理路径  
                string[] lines = System.IO.File.ReadAllLines(txtFile, Encoding.GetEncoding("gb2312"));
                //iTextSharp.text.PageSize.A4    自定义页面大小  
                iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 20, 20, 20);
                PdfWriter pdfwriter =
                    PdfWriter.GetInstance(doc, new FileStream(pdfFile, FileMode.Create));

                doc.Open();
                //创建我的基本字体  
                BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //创建字体      字体大小,字体粗細    字体颜色  
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                iTextSharp.text.Paragraph paragraph;
                foreach (string line in lines)
                {
                    paragraph = new iTextSharp.text.Paragraph(line, font);
                    doc.Add(paragraph);
                }

                //关闭文件  
                doc.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 把txt文件转换成pdf格式文件(备用)
        /// </summary>
        /// <param name="txtFile"></param>
        /// <param name="pdfFile"></param>
        /// <returns></returns>
        public bool TxtConvertPdf(string txtFile, string pdfFile)
        {
            bool result = false;
            try
            {
                var document = new iTextSharp.text.Document(PageSize.A4, 30f, 30f, 30f, 30f);
                PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
                document.Open();
                var bfSun = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var font = new iTextSharp.text.Font(bfSun, 12f);
                var objReader = new StreamReader(txtFile, Encoding.GetEncoding("gb2312"));
                var str = "";
                while (str != null)
                {
                    str = objReader.ReadLine();
                    if (str != null)
                    {
                        document.Add(new iTextSharp.text.Paragraph(str, font));
                    }
                }
                objReader.Close();
                document.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion
        #region 预览图片
        /// <summary>
        /// 预览图片
        /// </summary>
        public string PreviewPicture(string physicalPath, string url)
        {
            string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".pdf";
            if (!File.Exists(pdfPath))//不存在转pdf
            {
                if (ConvertJPG2PDF(physicalPath, pdfPath))//转换成功
                {
                    //预览pdf
                    return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
                }
                else
                {
                    //预览图片
                    return url;
                }
            }
            else
            {
                //预览pdf
                return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
            }
        }
        /// <summary>
        /// 把图片转换pdf格式文件
        /// </summary>
        /// <param name="jpgfile"></param>
        /// <param name="pdf"></param>
        /// <returns></returns>
        public bool ConvertJPG2PDF(string jpgfile, string pdf)
        {
            bool result = false;
            try
            {
                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
                using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    PdfWriter.GetInstance(document, stream);
                    document.Open();
                    using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var image = Image.GetInstance(imageStream);
                        if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
                        {
                            image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                        }
                        else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
                        {
                            image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                        }
                        image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                        document.Add(image);
                    }

                    document.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion
        #region 预览Pdf
        /// <summary>
        /// 预览Pdf
        /// </summary>
        public string PreviewPdf(string physicalPath, string url)
        {
            if (Util.GetFileExt(physicalPath).ToLower() == ".swf")
            {
                return url;
            }
            string swfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".swf";
            if (!File.Exists(swfPath))
            {
                Pdf2Swf(physicalPath, swfPath);
            }
            return url.Substring(0, url.LastIndexOf(.)) + ".swf";
        }

        //pwf2swf.exe 文件所在目录  
        private string Pdf2Swfexe = Util.BaseDirectory.TrimEnd(\\) + @"\Tools\pdf2swf\pdf2swf.exe";

        /// <summary>  
        /// 转换所有的页,图片质量80%  
        /// </summary>  
        /// <param name="pdfPath">PDF文件地址</param>  
        /// <param name="swfPath">生成后的SWF文件地址</param>  
        public bool Pdf2Swf(string pdfPath, string swfPath)
        {
            return Pdf2Swf(pdfPath, swfPath, 1, GetPageCount(pdfPath), 80);
        }

        /// <summary>  
        /// PDF格式转为SWF  
        /// </summary>  
        /// <param name="pdfPath">PDF文件地址</param>  
        /// <param name="swfPath">生成后的SWF文件地址</param>  
        /// <param name="beginpage">转换开始页</param>  
        /// <param name="endpage">转换结束页</param>  
        /// <param name="photoQuality"></param>  
        private bool Pdf2Swf(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
        {
            if (!System.IO.File.Exists(Pdf2Swfexe) ||
                !System.IO.File.Exists(pdfPath) ||
                System.IO.File.Exists(swfPath))
            {
                return false;
            }

            //执行的命令参数  
            StringBuilder command = new StringBuilder();

            command.AppendFormat("    \"{0}\"", pdfPath);
            command.AppendFormat(" -o \"{0}\"", swfPath);
            command.Append(" -s flashversion=9");
            command.AppendFormat(" -p \"{0}-{1}\"", beginpage, endpage);
            command.AppendFormat(" -j {0}", photoQuality);

            Process p = new Process
            {
                StartInfo =
                {
                    FileName = Pdf2Swfexe,
                    Arguments = command.ToString(),
                    WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/"),
                    WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    CreateNoWindow = false
                }
            };
            p.Start();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.Close();
            p.Dispose();

            return true;
        }

        /// <summary>  
        /// 取PDF总页数  
        /// </summary>  
        /// <param name="pdfPath">PDF文件地址</param>  
        private int GetPageCount(string pdfPath)
        {
            byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);

            if (buffer.Length <= 0)
            {
                return -1;
            }

            string pdfText = Encoding.Default.GetString(buffer);

            Regex rx1 = new Regex(@"/Type\s*/Page[^s]");
            MatchCollection matches = rx1.Matches(pdfText);
            if (matches.Count == 0)
            {
                //iTextSharp读取pdf页数
                PdfReader pdfReader = new PdfReader(pdfPath);
                if (pdfReader.NumberOfPages == 0)
                {
                    return 1;
                }
                return pdfReader.NumberOfPages;
            }
            return matches.Count;
        }

        #region 获取PDF文件的页数(废弃)

        private int BytesLastIndexOf(Byte[] buffer, int length, string Search)
        {
            if (buffer == null)
                return -1;
            if (buffer.Length <= 0)
                return -1;
            byte[] SearchBytes = Encoding.Default.GetBytes(Search.ToUpper());
            for (int i = length - SearchBytes.Length; i >= 0; i--)
            {
                bool bFound = true;
                for (int j = 0; j < SearchBytes.Length; j++)
                {
                    if (ByteUpper(buffer[i + j]) != SearchBytes[j])
                    {
                        bFound = false;
                        break;
                    }
                }
                if (bFound)
                    return i;
            }
            return -1;
        }

        private byte ByteUpper(byte byteValue)
        {
            char charValue = Convert.ToChar(byteValue);
            if (charValue < a || charValue > z)
                return byteValue;
            else
                return Convert.ToByte(byteValue - 32);
        }

        /// <summary>
        /// 获取pdf文件的页数
        /// </summary>
        public int GetPDFPageCount(string path) //获取pdf文件的页数
        {
            //path = HttpContext.Current.Server.MapPath(path);
            byte[] buffer = File.ReadAllBytes(path);
            int length = buffer.Length;
            if (buffer == null)
                return -1;
            if (buffer.Length <= 0)
                return -1;
            try
            {
                //Sample
                //      29 0 obj
                //      <</Count 9
                //      Type /Pages
                int i = 0;
                int nPos = BytesLastIndexOf(buffer, length, "/Type/Pages");
                if (nPos == -1)
                    return -1;
                string pageCount = null;
                for (i = nPos; i < length - 10; i++)
                {
                    if (buffer[i] == / && buffer[i + 1] == C && buffer[i + 2] == o && buffer[i + 3] == u && buffer[i + 4] == n && buffer[i + 5] == t)
                    {
                        int j = i + 3;
                        while (buffer[j] != / && buffer[j] != >)
                            j++;
                        pageCount = Encoding.Default.GetString(buffer, i, j - i);
                        break;
                    }
                }
                if (pageCount == null)
                    return -1;
                int n = pageCount.IndexOf("Count");
                if (n > 0)
                {
                    pageCount = pageCount.Substring(n + 5).Trim();
                    for (i = pageCount.Length - 1; i >= 0; i--)
                    {
                        if (pageCount[i] >= 0 && pageCount[i] <= 9)
                        {
                            return int.Parse(pageCount.Substring(0, i + 1));
                        }
                    }
                }
                return -1;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        #endregion
        #endregion
        #region 预览视频
        /// <summary>
        /// 预览视频
        /// </summary>
        public string PreviewVideo(string physicalPath, string url)
        {
            if (Util.GetFileExt(physicalPath).ToLower() == ".mp4")
            {
                return url;
            }
            string mp4Path = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".mp4";
            if (!File.Exists(mp4Path))
            {
                ConvertToMp4(physicalPath, mp4Path);
            }
            return url.Substring(0, url.LastIndexOf(.)) + ".mp4";
        }
        /// <summary>
        /// 格式转换(Mp4)
        /// </summary>
        /// <param name="pathBefore">原格式文件路径(绝对路劲)</param>
        /// <param name="pathLater">转换后文件路径(绝对路劲)</param>
        /// <returns></returns>
        public string ConvertToMp4(string pathBefore, string pathLater)
        {
            string c = Util.BaseDirectory.TrimEnd(\\) + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -y " + pathLater;
            string str = RunCmd(c);
            return str;
        }
        #endregion
        #region 预览html
        /// <summary>
        /// 预览html
        /// </summary>
        public string PreviewHtml(string physicalPath, string url)
        {
            string pdfPath = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".pdf";
            if (!File.Exists(pdfPath))//不存在
            {
                if (HtmlConvertToPdf(physicalPath, pdfPath))//转换成功
                {
                    //预览pdf
                    return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
                }
                else
                {
                    return url;
                }
            }
            else
            {
                //预览pdf
                return PreviewPdf(pdfPath, url.Substring(0, url.LastIndexOf(.)) + ".pdf");
            }
        }
        /// <summary>
        /// HTML文本内容转换为PDF
        /// </summary>
        /// <param name="strHtml">HTML文本内容</param>
        /// <param name="savePath">PDF文件保存的路径</param>
        /// <returns></returns>
        public bool HtmlTextConvertToPdf(string strHtml, string savePath)
        {
            bool flag = false;
            try
            {
                string htmlPath = HtmlTextConvertFile(strHtml);

                flag = HtmlConvertToPdf(htmlPath, savePath);
                File.Delete(htmlPath);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// HTML转换为PDF
        /// </summary>
        /// <param name="htmlPath">可以是本地路径,也可以是网络地址</param>
        /// <param name="savePath">PDF文件保存的路径</param>
        /// <returns></returns>
        public bool HtmlConvertToPdf(string htmlPath, string savePath)
        {
            bool flag = false;
            CheckFilePath(savePath);

            ///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下
            //string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";
            string exePath = Util.BaseDirectory.TrimEnd(\\) + @"\Tools\wkhtmltopdf\wkhtmltopdf.exe";
            if (!File.Exists(exePath))
            {
                throw new Exception("No application wkhtmltopdf.exe was found.");
            }

            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = exePath;
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                processStartInfo.UseShellExecute = false;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.Arguments = GetArguments(htmlPath, savePath);

                Process process = new Process();
                process.StartInfo = processStartInfo;
                process.Start();
                process.WaitForExit();

                ///用于查看是否返回错误信息
                //StreamReader srone = process.StandardError;
                //StreamReader srtwo = process.StandardOutput;
                //string ss1 = srone.ReadToEnd();
                //string ss2 = srtwo.ReadToEnd();
                //srone.Close();
                //srone.Dispose();
                //srtwo.Close();
                //srtwo.Dispose();

                process.Close();
                process.Dispose();

                flag = true;
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 获取命令行参数
        /// </summary>
        /// <param name="htmlPath"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private string GetArguments(string htmlPath, string savePath)
        {
            if (string.IsNullOrEmpty(htmlPath))
            {
                throw new Exception("HTML local path or network address can not be empty.");
            }

            if (string.IsNullOrEmpty(savePath))
            {
                throw new Exception("The path saved by the PDF document can not be empty.");
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(" --page-height 297 ");        //页面高度297mm(A4纸高度)
            stringBuilder.Append(" --page-width 210 ");         //页面宽度210mm(A4纸宽度)
            //stringBuilder.Append(" --header-center 我是页眉 ");  //设置居中显示页眉
            //stringBuilder.Append(" --header-line ");         //页眉和内容之间显示一条直线
            //stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" ");    //设置居中显示页脚
            //stringBuilder.Append(" --footer-line ");       //页脚和内容之间显示一条直线
            stringBuilder.Append(" " + htmlPath + " ");       //本地 HTML 的文件路径或网页 HTML 的URL地址
            stringBuilder.Append(" " + savePath + " ");       //生成的 PDF 文档的保存路径
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 验证保存路径
        /// </summary>
        /// <param name="savePath"></param>
        private void CheckFilePath(string savePath)
        {
            string ext = string.Empty;
            string path = string.Empty;
            string fileName = string.Empty;

            ext = Path.GetExtension(savePath);
            if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf")
            {
                throw new Exception("Extension error:This method is used to generate PDF files.");
            }

            fileName = Path.GetFileName(savePath);
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("File name is empty.");
            }

            try
            {
                path = savePath.Substring(0, savePath.IndexOf(fileName));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                throw new Exception("The file path does not exist.");
            }
        }

        /// <summary>
        /// HTML文本内容转HTML文件
        /// </summary>
        /// <param name="strHtml">HTML文本内容</param>
        /// <returns>HTML文件的路径</returns>
        public string HtmlTextConvertFile(string strHtml)
        {
            if (string.IsNullOrEmpty(strHtml))
            {
                throw new Exception("HTML text content cannot be empty.");
            }

            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"html\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000) + ".html";
                FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);
                streamWriter.Write(strHtml);
                streamWriter.Flush();

                streamWriter.Close();
                streamWriter.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                return fileName;
            }
            catch
            {
                throw new Exception("HTML text content error.");
            }
        }
        #endregion
        #region 预览音频
        /// <summary>
        /// 预览音频
        /// </summary>
        public string PreviewAudio(string physicalPath, string url)
        {
            if (Util.GetFileExt(physicalPath).ToLower() == ".mp3")
            {
                return url;
            }
            string mp3Path = physicalPath.Substring(0, physicalPath.LastIndexOf(.)) + ".mp3";
            if (!File.Exists(mp3Path))
            {
                ConvertToMp3(physicalPath, mp3Path);
            }
            return url.Substring(0, url.LastIndexOf(.)) + ".mp3";
        }
        /// <summary>
        /// 格式转换(Mp3)
        /// </summary>
        /// <param name="pathBefore">原格式文件路径(绝对路劲)</param>
        /// <param name="pathLater">转换后文件路径(绝对路劲)</param>
        /// <returns></returns>
        public string ConvertToMp3(string pathBefore, string pathLater)
        {
            string c = Util.BaseDirectory.TrimEnd(\\) + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -f mp3 -acodec libmp3lame -y " + pathLater;
            string str = RunCmd(c);
            return str;
        }
        /// <summary>
        /// 执行Cmd命令
        /// </summary>
        private string RunCmd(string c)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("cmd.exe");
                info.RedirectStandardOutput = false;
                info.UseShellExecute = false;
                System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.Start();
                p.StandardInput.WriteLine(c);
                p.StandardInput.AutoFlush = true;
                System.Threading.Thread.Sleep(1000);
                p.StandardInput.WriteLine("exit");
                p.Close();
                p.WaitForExit(1000);
                string outStr = p.StandardOutput.ReadToEnd();
                //p.Close();

                return outStr;
            }
            catch (Exception ex)
            {
                return "error" + ex.Message;
            }
        }
        #endregion
View Code

3.转换文件工具

预览 excel、word、txt、图片、pdf、html、音视频等文件(涉及到格式转换,用到ffmpeg、pdf2swf、wkhtmltopdf工具,iTextSharp类,Aspose(破解版)类、Microsoft.Office.Interop.Excel、Word类、swf文件预览插件FlexPaper)

 

C#文件网页预览: https://blog.csdn.net/lixiaoer757/article/details/80277617

net 预览文件 转换文件

标签:var   +=   display   pac   hmm   监听   portal   sleep   bug   

原文地址:https://www.cnblogs.com/love201314/p/9964977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!