word文档转换为PDF、jpg、HTML、txt、swf

来源:互联网 发布:淘宝素材图 编辑:程序博客网 时间:2024/05/18 00:12

好记性不如烂笔头,写下来以后参考

 word转换为PDF

  /// <summary>          
        /// 
        /// 把Word文件转换成为PDF格式文件    
        /// 
        /// </summary>       
        ///  <param name="sourcePath">源文件路径</param>       
        ///  <param name="targetPath">目标文件路径</param>       
        ///  <returns>true=转换成功</returns>     
        private bool WordToPDF(string sourcePath, string targetPath)
        {
            if (!File.Exists(sourcePath))
            {
                return false;
            }
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            bool result = false;
            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.ApplicationClass application = null;
            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                application = new Microsoft.Office.Interop.Word.ApplicationClass();
                application.Visible = false;
                document = application.Documents.Open(sourcePath);


                document.SaveAs();
                // document.SaveAs2();                
                document.ExportAsFixedFormat(targetPath, exportFormat);
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {


                if (document != null)
                {
                    document.Close();
                    document = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();


                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            } return result;
        }

word 转换为swf(需先将word转换为PDF),在网上下载swftools,安装之后把程序目录下的文件拷到程序目录下就可以了

  /// <summary>
        /// PDF格式转为SWF
        /// </summary>
        /// <param name="pdfPath">PDF文件地址</param>
        /// <param name="swfPath">生成后的SWF文件地址</param>
        /// <param name="beginpage">转换开始页</param>
        /// <param name="endpage">转换结束页</param>
        private bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
        {
            try
            {
                //需更改
                string exe = Application.StartupPath + "\\SWFTools\\pdf2swf.exe";
                // string exe = @"D:\Program Files (x86)\SWFTools\pdf2swf.exe";
                if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath))
                {
                    return false;
                }
                if (File.Exists(swfPath))
                {
                    File.Delete(swfPath);
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" \"" + pdfPath + "\"");
                // 指定输出的swf文件名
                sb.Append(" -o \"" + swfPath + "\"");
                // 设置SWF转码时候的参数,具体参数可以用pdf2swf -s help获取
                sb.Append(" -s flashversion=9");
                sb.Append(" -s languagedir=\"E:\\xpdf\\xpdf-chinese-simplified\"");
                if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
                // 指定打开pdf的密码
                sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\""); 
                // 设置转换其中的jpeg图片的质量
                sb.Append(" -j " + photoQuality);
                string Command = sb.ToString();
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = exe;
                p.StartInfo.Arguments = Command;
                // p.StartInfo.WorkingDirectory = "~/Bin/"; 
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.BeginErrorReadLine();
                p.WaitForExit();
                p.Close();
                p.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }


        /// <summary>
        /// 返回页数
        /// </summary>
        /// <param name="pdfPath">PDF文件地址</param>
        private int GetPageCount(string pdfPath)
        {
            byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);
            int length = buffer.Length;
            if (buffer == null)
                return -1;
            if (buffer.Length <= 0)
                return -1;
            string pdfText = Encoding.Default.GetString(buffer);
            System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");
            System.Text.RegularExpressions.MatchCollection matches = rx1.Matches(pdfText);
            return matches.Count;
        }

word转换为jpg

  /// <summary>
        /// pdf转换成jpg
        /// </summary>
        /// <param name="pdfInputPath">输入文件路径</param>
        /// <param name="imageOutputPath">输出文件路径</param>
        /// <param name="imageName">图片名称</param>
        public static bool pdfToImage(string pdfInputFullName, string imageOutputPath,int flag)
        {
            bool success = true;
            try
            {
                string imageName = Path.GetFileNameWithoutExtension(pdfInputFullName);
                PDFFile pdfFile = PDFFile.Open(pdfInputFullName);
                ImageFormat imageFormat = ImageFormat.Jpeg;
                if (!Directory.Exists(imageOutputPath))
                {
                    Directory.CreateDirectory(imageOutputPath);
                }
                Bitmap pageImage = pdfFile.GetPageImage(0, 56 * 2);
                pageImage.Save(imageOutputPath+"\\" + imageName + "." + "jpg", imageFormat);
                pageImage.Dispose();
                pdfFile.Dispose();
                if(flag==(int)wordOrPdf .word )//1代表源文件为pdf,2代表源文件为word
                    File.Delete(pdfInputFullName);
            }
            catch
            {
                success = false;
            }
            return success;
        }

word 转换为HTML

 /// <summary>
        /// word文档转换为HTML文件
        /// </summary>
        /// <param name="inDocPath">输入word路径</param>
        /// <param name="outHtmlPath">输出HTML路径</param>
        /// <param name="message">转换信息</param>
        /// <returns>true=转换成功</returns>
        public static bool Word2Html(string inDocPath, string outHtmlPath, out string message)
        {
            try
            {
                if (!inDocPath.EndsWith(".doc") && !inDocPath.EndsWith(".docx"))
                {
                    message = "输入的不是标准文档格式文件!请重新输入";
                    return false;
                }
                if (File.Exists(outHtmlPath))
                {
                    File.Delete(outHtmlPath);
                }
                Application newApp = new Microsoft.Office.Interop.Word.Application();
                Document doc = null;
                // 缺省参数 
                object Unknown = Type.Missing;


                //为了保险,只读方式打开 
                object readOnly = true;
                // 指定另存为格式(html) 
                object formatHtml = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
                object sourcePath = inDocPath;
                object targetHtml = outHtmlPath;
                // 打开doc文件 
                doc = newApp.Documents.Open(ref sourcePath, ref Unknown, ref readOnly,
                    ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                //另存为HTML
                doc.SaveAs(ref targetHtml, ref formatHtml,
                      ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
                      ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                message = "转换为HTML成功!";
                return true;
            }
            catch (Exception ex)
            {
                message = "转换为HTML失败!" + ex.Message;
                return false;
            }
        }


word转换为txt

 /// <summary>
        /// word文档转换为txt文件
        /// </summary>
        /// <param name="inDocPath">输入word路径</param>
        /// <param name="outTxtPath">输出txt路径</param>
        /// <param name="message">显示信息</param>
        /// <returns>true=转换成功</returns>
        public static bool Word2Txt(string inDocPath, string outTxtPath, out string message)
        {
            try
            {
                if (!inDocPath.EndsWith(".doc") && !inDocPath.EndsWith(".docx"))
                {
                    message = "输入的不是标准文档格式文件!请重新输入";
                    return false;
                }
                if (File.Exists(outTxtPath))
                {
                    File.Delete(outTxtPath);
                }
                Application newApp = new Microsoft.Office.Interop.Word.Application();
                Document doc = null;
                // 缺省参数 
                object Unknown = Type.Missing;


                //为了保险,只读方式打开 
                object readOnly = true;
                // 指定另存为格式(Txt) 
                object formatTxt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatText;
                object sourcePath = inDocPath;
                object targetTxt = outTxtPath;
                // 打开doc文件 
                doc = newApp.Documents.Open(ref sourcePath, ref Unknown, ref readOnly,
                    ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                //另存为Txt
                doc.SaveAs(ref targetTxt, ref formatTxt,
                        ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                message = "转换为Txt成功!";
                return true;
            }
            catch (Exception ex)
            {
                message = "转换为Txt失败!" + ex.Message;
                return false;
            }
        }

0 1