C#調用WPS轉換文檔到PDF的的實現代碼。


1、WPS安裝,最好用這個版本別的版本不清楚,安裝Pro Plus2016版本。

https://ep.wps.cn/product/wps-office-download.html

 

2、添加相關的引用:wpsapiex.dll,etapi.dll,wppapi.dll,wpsapi.dll,目前就發現這幾個

 

 

 

3、代碼類如下

    /// <summary>
    /// WPS文件轉Pdf類
    /// </summary>
    public class ToPdfHelper : IDisposable
    {
        /// <summary>
        /// 是否殺死全部WPS程序
        /// </summary>
        public bool IsKillAllWps = false;
        //Wps的動態對象
        dynamic wps;
        /// <summary>
        /// 初始化類基礎信息
        /// </summary>
        /// <param name="FilePath">文件路徑</param>
        /// <param name="IsKillAllWps">轉換完成后是否殺死全部WPS應用</param>
        public ToPdfHelper(string FilePath, bool IsKillAllWps = false)
        {
            if (File.Exists(FilePath))
            {
                this.IsKillAllWps = IsKillAllWps;
                this.FilePath = FilePath;
                string Extension = Path.GetExtension(FilePath).ToLower();//擴展名 ".aspx"
                switch (Extension)
                {
                    case "xls":
                        Extension = "KET.Application";
                        break;
                    case "xlsx":
                        Extension = "KET.Application";
                        break;
                    case "ppt":
                        Extension = "KWPP.Application";
                        break;
                    case "pptx":
                        Extension = "KWPP.Application";
                        break;
                    default:
                        Extension = "KWps.Application";
                        break;
                }
                Type type = Type.GetTypeFromProgID(Extension);
                if (type == null)
                {
                    Extension = "wps.Application";
                    type = Type.GetTypeFromProgID("wps.Application");
                }
                wps = Activator.CreateInstance(type);
                //比較完整的一些
                //WPS文字           KWPS.Aplication
                //WPS的Excel        KET.Application
                //WPS的演示文檔     KWPP.Application
                //Word              Word.Application
                //Excel             Excel.Application
                //Powerpoint        Powerpoint.Application
            }
            else
            {
                throw new Exception("找不到原文件,請檢查!");
            }
        }
        /// <summary>
        /// 源文件路徑
        /// </summary>
        public string FilePath { get; set; }
        /// <summary>
        /// 使用wps將Word轉PDF
        /// </summary>
        /// <param name="TargetPath">目標文件路徑,不傳默認在源文件的所屬目錄</param>
        /// <returns>Pdf文件路徑</returns>
        public string WordWpsToPdf(string TargetPath = "")
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                throw new Exception("請傳入文件路徑");
            }
            //如果沒傳入文件路徑就默認使用源目錄
            if (string.IsNullOrEmpty(TargetPath))
            {
                TargetPath = Path.ChangeExtension(FilePath, "pdf");
            }
            try
            {
                //忽略警告提示
                wps.DisplayAlerts = false;
                //用wps 打開word不顯示界面
                dynamic doc = wps.Documents.Open(FilePath, Visible: false);
                //保存為Pdf
                doc.ExportAsFixedFormat(TargetPath, Word.WdExportFormat.wdExportFormatPDF);
                //設置隱藏菜單欄和工具欄
                //wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return TargetPath;
        }
        /// <summary>
        /// 使用wps將xls轉PDF
        /// </summary>
        /// <param name="TargetPath">目標文件路徑,不傳默認在源文件的所屬目錄</param>
        /// <returns>Pdf文件路徑</returns>
        public string XlsWpsToPdf(string TargetPath = "")
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                throw new Exception("請傳入文件路徑");
            }
            //如果沒傳入文件路徑就默認使用源目錄
            if (string.IsNullOrEmpty(TargetPath))
            {
                TargetPath = Path.ChangeExtension(FilePath, "pdf");
            }
            try
            {
                XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF;
                object missing = Type.Missing;
                //忽略警告提示
                wps.DisplayAlerts = false;
                //xls 轉pdf
                dynamic doc = wps.Application.Workbooks.Open(FilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //保存為Pdf
                doc.ExportAsFixedFormat(targetType, TargetPath, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                //設置隱藏菜單欄和工具欄
                //wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return TargetPath;
        }

        /// <summary>
        /// 使用ppt將xls轉PDF
        /// </summary>
        /// <param name="TargetPath">目標文件路徑,不傳默認在源文件的所屬目錄</param>
        /// <returns>Pdf文件路徑</returns>
        public string PptWpsToPdf(string TargetPath = "")
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                throw new Exception("請傳入文件路徑");
            }
            //如果沒傳入文件路徑就默認使用源目錄
            if (string.IsNullOrEmpty(TargetPath))
            {
                TargetPath = Path.ChangeExtension(FilePath, "pdf");
            }
            try
            {
                //忽略警告提示
                wps.DisplayAlerts = false;
                //ppt 轉pdf
                dynamic doc = wps.Presentations.Open(FilePath, MsoTriState.msoCTrue,
                    MsoTriState.msoCTrue, MsoTriState.msoCTrue);
                object missing = Type.Missing;
                //doc.ExportAsFixedFormat(pdfPath, PpFixedFormatType.ppFixedFormatTypePDF,
                //    PpFixedFormatIntent.ppFixedFormatIntentPrint,
                //    MsoTriState.msoCTrue, PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst,
                //    PpPrintOutputType.ppPrintOutputBuildSlides,
                //      MsoTriState.msoCTrue, null, PpPrintRangeType.ppPrintAll,"",
                //      false, false, false, false, false, missing);
                //保存為Pdf
                doc.SaveAs(TargetPath, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
                //設置隱藏菜單欄和工具欄
                //wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return TargetPath;
        }

        /// <summary>
        /// 支持釋放資源可以使用using
        /// </summary>
        public void Dispose()
        {
            if (wps != null)
            {
                wps.Quit();
                //釋放掉wps對象
                wps = null;
                #region 強制關閉所有wps的功能慎用,尤其是帶並發的
                //強制關閉所有wps進程,解決文件占用的問題
                if (this.IsKillAllWps)
                {
                    System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("wps");
                    foreach (System.Diagnostics.Process prtemp in process)
                    {
                        prtemp.Kill();
                    }
                } 
                #endregion
            }
        }
    }

3、調用代碼如下

        /// <summary>
        /// 開始轉換Pdf
        /// </summary>
        private void StatButton_Click(object sender, EventArgs e)
        {
            if (File.Exists(PdfFileTextBox.Text)&& Path.IsPathRooted(PdfFileTextBox.Text))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                using (ToPdfHelper Help = new ToPdfHelper(PdfFileTextBox.Text,true))
                {
                    Help.WordWpsToPdf();
                }
                sw.Stop();
                TimeSpan ts2 = sw.Elapsed;
                TimeLabel.Text = string.Format("轉換使用時間:總共花費{0}ms.", ts2.TotalMilliseconds);
            }
            else
            {
                MessageBox.Show("文件不存在,檢查文件路徑是否正常,只支持絕對路徑!");
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM