將office檔和tif檔轉化為pdf檔(C#代碼)

參考網址: 

Microsoft.Office.Interop.PowerPoint Namespace 

 http://msdn.microsoft.com/en-us/library/microsoft.office.interop.powerpoint.aspx

Microsoft.Office.Interop.Word Namespace

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.aspx

Microsoft.Office.Interop.Excel Namespace

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx

 

 

首先需要引用word、excel、powerpoint的dll以及office.dll

using Word = Microsoft.Office.Interop.Word;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Excel = Microsoft.Office.Interop.Excel;

 

安裝Bullzip PDF Printer(將office轉化為pdf)和ImageMagick(將tif轉化為pdf)

 

主要代碼

#region doc、xls、ppt、tiff格式转换函数

        private string ConvertPpt2Pdf(string sourceFile)
        {

            if (!File.Exists(sourceFile))
            {
                throw new Exception(string.Format("File not found:{0}", sourceFile));
            }
            string strDir = Path.GetDirectoryName(sourceFile);
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string psFileName = string.Format("{0}//{1}.ps", strDir, currentTime);
            string pdfFileName = string.Format("{0}//{1}.pdf", strDir, currentTime);
            string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFile);
            string resultPdfFileName = string.Format("{0}//{1}.pdf", strDir, FileNameWithoutExtension);

            PowerPoint.ApplicationClass powerpoint = null;
            powerpoint.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            PowerPoint.Presentation ppt = null;
             string pageNum = null;
            try
            {

                powerpoint = new PowerPoint.ApplicationClass();
                ppt = powerpoint.Presentations.Open(sourceFile,
                 Microsoft.Office.Core.MsoTriState.msoFalse,
                 Microsoft.Office.Core.MsoTriState.msoTrue,
                 Microsoft.Office.Core.MsoTriState.msoFalse);

                string oldPrinter = ppt.PrintOptions.ActivePrinter;
                ppt.PrintOptions.ActivePrinter = "Bullzip PDF Printer";

                pageNum = ppt.Slides.Count.ToString();
                 Response.Write("The   number   of   pages   in   ppt   is   {0} " + pageNum);
                ppt.PrintOut(-1, -1, psFileName, 1, Microsoft.Office.Core.MsoTriState.msoTrue);
                ppt.PrintOptions.ActivePrinter = oldPrinter;

                int t = 5;
                while (!File.Exists(psFileName) && t > 0)
                {
                    System.Threading.Thread.Sleep(100);
                    t--;
                   
                }

                int i = 3;
                long currentLength = 0;
                string length = null;
                while (i > 0)
                {
                   
                    currentLength = new FileInfo(psFileName).Length;
                    if (currentLength == 0)
                        continue;
                    if (length == currentLength.ToString())
                    {
                        i--;
                    }
                    else
                    {
                        length = currentLength.ToString();
                    }
                    System.Threading.Thread.Sleep(200);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (ppt != null)
                {
                    ppt.Close();
                    ppt = null;
                }
                if (powerpoint != null)
                {
                    powerpoint.Quit();
                    powerpoint = null;
                }
            }
            try
            {
                if (File.Exists(psFileName))
                {
                    ConvertPs2Pdf(psFileName);
                }
                System.Threading.Thread.Sleep(1000);
                if (File.Exists(psFileName))
                {
                    while (IsFileInUse(psFileName))
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    File.Delete(psFileName);
                }
                if (File.Exists(pdfFileName))
                {
                    while (IsFileInUse(pdfFileName))
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    File.Move(pdfFileName, resultPdfFileName);
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (!File.Exists(resultPdfFileName))
                {
                    int n = 20;

                    while (!File.Exists(pdfFileName) && n > 0)
                    {
                        System.Threading.Thread.Sleep(100);
                        n--;
                    }
                    if (File.Exists(pdfFileName))
                    {
                        while (IsFileInUse(pdfFileName))
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        File.Delete(pdfFileName);
                    }
                }

            }
            return resultPdfFileName;

        }

         

 

         private string ConvertXls2Pdf(string sourceFile)
        {
            if (!File.Exists(sourceFile))
                throw new Exception(string.Format("File not found:{0}", sourceFile));

            string strDir = Path.GetDirectoryName(sourceFile);
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string psFileName = string.Format("{0}//{1}.ps", strDir, currentTime);
            string pdfFileName = string.Format("{0}//{1}.pdf", strDir, currentTime);
            string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFile);
            string resultPdfFileName = string.Format("{0}//{1}.pdf", strDir, FileNameWithoutExtension);

            object UpdateLinks = new object[] { 2 };
            object;
            object Format = System.Reflection.Missing.Value;
            object Password = System.Reflection.Missing.Value;
            object WriteResPassword = System.Reflection.Missing.Value;
            object IgnoreReadOnlyRecommended = false;
            object Origin = Excel.XlPlatform.xlWindows;
            object Delimiter = System.Reflection.Missing.Value;
            object Editable = false;
            object Notify = true;
            object Converter = System.Reflection.Missing.Value;
            object AddToMru = System.Reflection.Missing.Value;
            object Local = System.Reflection.Missing.Value;
            object CorruptLoad = System.Reflection.Missing.Value;

            object From = System.Reflection.Missing.Value;
            object To = System.Reflection.Missing.Value;
            object Copies = System.Reflection.Missing.Value;
            object Preview = System.Reflection.Missing.Value;
            object ActivePrinter = "Bullzip PDF Printer";
            object PrintToFile = true;
            object Collate = true;
            object PrToFileName = psFileName;
            object SaveChanges = false;

            // string pageNum = null;

            Excel.Application excel = null;
            Excel.Workbook xls = null;
            try
            {
                excel = new Excel.Application();
                xls = excel.Workbooks.Open(sourceFile, UpdateLinks, ReadOnly, Format, Password,
                              WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable,
                              Notify, Converter, AddToMru, Local, CorruptLoad);

                //MessageBox.Show("count: " + xls.Worksheets.Count.ToString());
                // pageNum = xls.Application.ExecuteExcel4Macro("Get.Document(50)").ToString();
                // Response.Write("The   number   of   pages   in   xls   is   {0} " + pageNum);

                //MessageBox.Show("VPageBreaks count: " + xls.Worksheets.VPageBreaks.get_Item(1).);
                //xls.Worksheets.HPageBreaks.Add(Excel.Range);
                // MessageBox.Show("HPageBreaks count: " + xls.Worksheets.HPageBreaks.Count.ToString());
                // xls.Worksheets.VPageBreaks.Add(Excel.Range);
                // MessageBox.Show("VPageBreaks count: " + xls.Worksheets.VPageBreaks.Count.ToString());

                xls.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName);

                int t = 5;
                while (!File.Exists(psFileName) && t > 0)
                {
                    System.Threading.Thread.Sleep(100);
                    t--;
                }

                int i = 3;
                long currentLength = 0;
                string length = null;
                while (i > 0)
                {
                    currentLength = new FileInfo(psFileName).Length;
                    if (currentLength == 0)
                        continue;
                    if (length == currentLength.ToString())
                    {
                        i--;
                    }
                    else
                    {
                        length = currentLength.ToString();
                    }
                    System.Threading.Thread.Sleep(200);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (xls != null)
                {
                    xls.Close(SaveChanges, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                    xls = null;
                }
                if (excel != null)
                {
                    excel.Quit();
                    excel = null;
                }
            }

            try
            {
                if (File.Exists(psFileName))
                {
                    ConvertPs2Pdf(psFileName);
                }

                System.Threading.Thread.Sleep(1000);
                if (File.Exists(psFileName))
                {
                    while (IsFileInUse(psFileName))
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    File.Delete(psFileName);
                }
                if (File.Exists(pdfFileName))
                {
                    while (IsFileInUse(pdfFileName))
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    File.Move(pdfFileName, resultPdfFileName);
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                 if (!File.Exists(resultPdfFileName))
                {
                    int n = 20;

                    while (!File.Exists(pdfFileName) && n > 0)
                    {
                        System.Threading.Thread.Sleep(100);
                        n--;
                    }
                    if (File.Exists(pdfFileName))
                    {
                        while (IsFileInUse(pdfFileName))
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        File.Delete(pdfFileName);
                    }
                }

            }

            return resultPdfFileName;

        }


        private string ConvertDoc2Pdf(string sourceFile)
        {
            if (!File.Exists(sourceFile))
                throw new Exception(string.Format("File not found:{0}", sourceFile));

            string strDir = Path.GetDirectoryName(sourceFile);
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string psFileName = string.Format("{0}//{1}.ps", strDir, currentTime);
            string pdfFileName = string.Format("{0}//{1}.pdf", strDir, currentTime);
            string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFile);
            string resultPdfFileName = string.Format("{0}//{1}.pdf", strDir, FileNameWithoutExtension);

            object objPsFile = (object)psFileName;
            object background = false;
            object PageType = Word.WdPrintOutPages.wdPrintAllPages;
            object printToFile = true;
            object collate = true;
            object append = false;
            object copies = false;
            object range = Word.WdPrintOutRange.wdPrintAllDocument;
            object missing = System.Reflection.Missing.Value;

            Word._Application word = null;
            object fileName = sourceFile;
            object SaveChanges = false;
            Word.Document doc = null;
            //int pageNum = 0;

            try
            {
                // 打开Word文档
                word = new Word.Application();
                doc = word.Documents.Open(ref fileName,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing);

                string oldPrinter = doc.Application.ActivePrinter;
                doc.Application.ActivePrinter = "Bullzip PDF Printer";

                //Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                // pageNum = doc.ComputeStatistics(stat, ref   missing);
                // Response.Write("The   number   of   pages   in   doc   is   {0} " + pageNum.ToString());

                // Word文档打印到Ps文件
                doc.PrintOut(ref background, ref append, ref range, ref objPsFile, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref PageType, ref printToFile, ref collate, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing);

                doc.Application.ActivePrinter = oldPrinter;

                int t = 5;
                while (!File.Exists(psFileName) && t > 0)
                {
                    System.Threading.Thread.Sleep(100);
                    t--;
                }

                int i = 3;
                long currentLength = 0;
                string length = null;
                while (i > 0)
                {
                    currentLength = new FileInfo(psFileName).Length;
                    if (currentLength == 0)
                        continue;
                    if (length == currentLength.ToString())
                    {
                        i--;
                    }
                    else
                    {
                        length = currentLength.ToString();
                    }
                    System.Threading.Thread.Sleep(200);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close(ref SaveChanges, ref missing, ref missing);
                    doc = null;
                }
                if (word != null)
                {
                    word.Quit(ref SaveChanges, ref missing, ref missing);
                    word = null;
                }
            }
            try
            {
                if (File.Exists(psFileName))
                {
                    ConvertPs2Pdf(psFileName);
                }

                System.Threading.Thread.Sleep(1000);
                if (File.Exists(psFileName))
                {
                    while (IsFileInUse(psFileName))
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    File.Delete(psFileName);
                }
                if (File.Exists(pdfFileName))
                {
                    while (IsFileInUse(pdfFileName))
                    {
                        System.Threading.Thread.Sleep(200);
                    }
                    File.Move(pdfFileName, resultPdfFileName);
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                /*if (File.Exists(psFileName))
                {
                    int t = 10;
                    while (IsFileInUse(psFileName) && t > 0)
                    {
                        System.Threading.Thread.Sleep(100);
                        t--;
                    }
                    File.Delete(psFileName);
                }*/
                if (!File.Exists(resultPdfFileName))
                {
                    int n = 20;

                    while(!File.Exists(pdfFileName) && n > 0)
                    {
                        System.Threading.Thread.Sleep(100);
                        n--;
                    }
                    if (File.Exists(pdfFileName))
                    {
                        while (IsFileInUse(pdfFileName))
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        File.Delete(pdfFileName);
                    }
                }
            }

            return resultPdfFileName;
               
       }

 

        // Ps转PDF
        public void ConvertPs2Pdf(string psFile)
        {
            Process objProcess = new Process();
            objProcess.StartInfo.CreateNoWindow = true;
            objProcess.StartInfo.UseShellExecute = true;
            objProcess.StartInfo.FileName = "ps2pdf14";
            objProcess.StartInfo.Arguments = psFile;
            objProcess.Start();
           // objProcess.WaitForExit();
        }

 

        // tiff转PDF
        public string ConvertTif2Pdf(string sourceFile)
        {
            string strDir = Path.GetDirectoryName(sourceFile);
            string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFile);
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string SourceFileNameToChange = string.Format("{0}//{1}.tif", strDir, currentTime);
            string pdfFileName = string.Format("{0}//{1}.pdf", strDir, currentTime);
            if (File.Exists(sourceFile))
            {
                File.Move(sourceFile, SourceFileNameToChange);
            }
            string resultPdfFileName = string.Format("{0}//{1}.pdf", strDir, FileNameWithoutExtension);
            Process objProcess = new Process();
            objProcess.StartInfo.CreateNoWindow = true;
            objProcess.StartInfo.UseShellExecute = true;
            objProcess.StartInfo.FileName = "/"C://Program Files//ImageMagick-6.5.7-Q16//convert/"";  //需要先安裝ImageMagick

            objProcess.StartInfo.Arguments =  Path.GetFileName(SourceFileNameToChange) + " " + Path.GetFileName(pdfFileName);
            objProcess.StartInfo.WorkingDirectory = strDir;
            objProcess.Start();
            objProcess.WaitForExit();
            if (File.Exists(pdfFileName))
            {
                File.Move(pdfFileName, resultPdfFileName);
            }
            if (File.Exists(SourceFileNameToChange))
            {
                File.Move(SourceFileNameToChange, sourceFile);
            }
            return resultPdfFileName;
        }

        public bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            if (File.Exists(fileName))
            {
                FileStream fs = null;
                try
                {
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                    inUse = false;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message.ToString());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                return inUse;           //true表示正在使用,false没有使用
            }
            else
            {
                return false;           //文件不存在则一定没有被使用
            }
        }
        #endregion

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值