C#文件网页预览

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


前端代码(页面接收预览URL):

使用vue.js
如果是Word转成html、Excel转成html、txt、html、htm 类型文件直接指向后端返回路径
<iframe class="frameMain" :src="urlIframe" frameborder="0"
                                v-bind:style="{ 'height': mainHeight - 140 + 'px','width':'100%'}"></iframe>

js代码:

resp.Data.RelativePaths//服务器断返回的预览路径(带IP地址和端口号)
resp.Data.DocType//服务器端返回的文件类型
cur.urlIframe = "FilePreview";
let path = !!resp.Data.RelativePaths ? "http://" + resp.Data.RelativePaths : "";
//1 video, 2 img, 3 audio, 4-1 doc-html,4-2 doc-swf, 5-1 xls-html,5-2 xls-swf, 6 txt,7 html/htm, 8 pdf
switch (resp.Data.DocType) {
    case "1":
        cur.urlIframe = "FilePreview?fileType=" + resp.Data.DocType + "&filePath=" + path;
        break;
    case "2":
        cur.urlIframe = "FilePreview?fileType=" + resp.Data.DocType + "&filePath=" + path;
        break;
    case "3":
        cur.urlIframe = "FilePreview?fileType=" + resp.Data.DocType + "&filePath=" + path;
        break;
    case "4-2":
    case "5-2":
    case "8":
        cur.urlIframe = "PdfPreview?fileType=" + resp.Data.DocType + "&filePath=" + path;
        break;
    case "4-1":
    case "5-1":
    case "6":
    case "7":
        cur.urlIframe = path;
        break;
}
controller代码
//预览文件(图片、音视频文件)
public ActionResult FilePreview(string fileType, string filePath)
{
    ViewBag.fileType = fileType;
    ViewBag.filePath = filePath;
    return View();
}
//预览Pdf、Word、Excel(都转换成swf预览)
public ActionResult PdfPreview(string fileType, string filePath)
{
    ViewBag.fileType = fileType;
    ViewBag.filePath = filePath;
    return View();
}
FilePreview 预览文件(图片、音视频文件)代码,后端用到ffmpeg工具
@{
    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"://图片
                        //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>
PdfPreview 预览Pdf、Word、Excel(都转换成swf预览),后端用到iTextSharp类,Microsoft.Office.Interop.Excel、Word类,前端用到swf文件预览插件
@{
    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:41726/tmp/94D1390E-930D-4D41-BD88-72FDC3273755/94D1390E-930D-4D41-BD88-72FDC3273755.pdf";
    //var swf = "C:/Users/jx2//Desktop/File/hu.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: false,
            FullScreenAsMaxWindow: false,
            ProgressiveLoading: true,
            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", "flashContent",
            "100%", (window.innerHeight - 25) + "px",
            swfVersionStr, xiSwfUrlStr,
            flashvars, params, attributes);
        swfobject.createCSS("#flashContent", "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>


后端代码:

using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;


#region 工具类
/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
private 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;
}    
//程序当前路径
private string BaseDirectory
{
    get
    {
        string _appPath = AppDomain.CurrentDomain.BaseDirectory;
        if (!_appPath.EndsWith(@"\")) _appPath = _appPath + @"\";
        return _appPath;
    }
}
//图片
private string[] imgExts = new string[] { ".BMP", ".GIF", ".JPEG", ".JPG", ".PNG", ".TIFF", ".TIF" };

/// <summary>
/// 获取文件的扩展名,格式为".txt"、".gif"、".docx"等
/// </summary>
/// <param name="fileName">文件名称(可以包含路径)</param>
/// <returns>返回扩展名,格式为".txt"、".gif"、".docx"等</returns>
private string GetFileExt(string fileName)
{
    string result = string.Empty;


    if (!string.IsNullOrEmpty(fileName))
    {
        int index = fileName.LastIndexOf('.');
        if (index > 0)
        {
            result = fileName.Substring(index);
        }
    }


    return result;
}
#endregion

/// <summary>
/// 文件预览
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "POST")]
[MyAuthorize("")]
[HttpPost, Route("FilePreview")]
public VMResult<VMFilePreview> FilePreview(参数)
{
    //获取文件路径代码start
    //根据参数获取到文件路径
    string tmpName = BaseDirectory.TrimEnd('\\') + "\\tmp\\" + doc.DocGuid + "\\" + doc.DocGuid + GetFileExt(doc.DocName);
    //如:/tmp/folderName/fileName.pdf
        //本文为以下路径
    result.Data.RelativePaths = "tmp\\" + doc.DocGuid + "\\" + doc.DocGuid + GetFileExt(doc.DocName);
    //获取文件路径代码end
    VMResult<VMFilePreview> result = new VMResult<VMFilePreview>();
    try
    {
        result.Data.RelativePaths = (HttpContext.Current.Request.Url.Authority + "\\" + Index(result.Data.RelativePaths)).Replace("\\", "/");
        string fileext = GetFileExt(doc.DocName).ToLower();
        if (imgExts.Contains(fileext.ToUpper()))//图片
        {
            result.Data.DocType = "2";
        }
        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 (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 (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))//文本
        {
            result.Data.DocType = "6";
        }
        else if (".html;.htm".Contains(fileext))//网页
        {
            result.Data.DocType = "7";
        }
        else if (".pdf;.swf".Contains(fileext))//pdf
        {
            result.Data.DocType = "8";
        }
    }
    catch (Exception ex)
    {
        Logger.Error(ex);
        result.ErrCode = 1;
        result.ResultMsg = "获取文件失败!";
    }
    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 (XLSConvertToPDF(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格式文件
/// </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;
}
#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 (DOCConvertToPDF(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格式文件
/// </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;
}
#endregion
#region 预览Txt
/// <summary>
/// 预览Txt
/// </summary>
public string PreviewTxt(string physicalPath, string url)
{
    return url;
}
#endregion
#region 预览图片
/// <summary>
/// 预览图片
/// </summary>
public string PreviewPicture(string physicalPath, string url)
{
    return url;
}
#endregion
#region 预览Pdf
/// <summary>
/// 预览Pdf
/// </summary>
public string PreviewPdf(string physicalPath, string url)
{
    if (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 const string Pdf2Swfexe = @"C:\Program Files (x86)\SWFTools\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 (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 = "c:\\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)
{
    return url;
}
#endregion
#region 预览音频
/// <summary>
/// 预览音频
/// </summary>
public string PreviewAudio(string physicalPath, string url)
{
    if (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 = "c:\\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


iTextSharp类,Microsoft.Office.Interop.Excel、Word类、swf文件预览插件:

https://download.csdn.net/download/lixiaoer757/10418308


SWFTOOLS PDF2SWF 参数详解:

https://blog.csdn.net/lixiaoer757/article/details/80338037


ffmpeg工具下载地址:

https://download.csdn.net/download/lixiaoer757/10413416

ffmpeg工具详解:

https://blog.csdn.net/lixiaoer757/article/details/80311305


猜你喜欢

转载自blog.csdn.net/lixiaoer757/article/details/80277617
今日推荐