用C#实现实时监测文件夹,把word/excel/ppt自动转为pdf

博主分享了一个用C#编写的WinForm程序,该程序监控指定目录,自动将上传的Office文档转换为PDF。程序避免了使用COM组件或OpenOffice,减少了转换过程中的问题。通过Aspose组件实现转换,已在服务器稳定运行一个月。
摘要由CSDN通过智能技术生成

很久没更新了,前段时间在准备软考,最近也忙着单位新系统的开发。所以也就没更新了,等后面几个项目做好了,我在项目分享出来!!

由于新开发的信息系统,原来旧版的信息系统,在查看文件时,都需要下载到本地,然后在打开查看,这样比较繁琐,所以在新版信息系统里,用了pdfjs插件进行在线查看文档,那么问题来了,怎么样才能把用户上传上来的office文档转为pdf呢??这个问题我采取了用php调用office的com组件进行转换。转换出来的pdf文件跟源文件基本一致,算是比较完美。但是com组件总会出现这个那个的问题。最后还是放弃了这个方案。第二个方案是安装调用openoffice组件,跟上面的差不多,虽然问题解决了,但是转换的效果很差,唉~~~~现在来说说我最终的方案吧!

现在这个方案是单独用C#写个winform程序,这个程序一直监控上传的目录,当目录有新的office文档上传时,程序直接把这些文件自动生成对应文件名的pdf,也就是test.doc同时生成test.doc.pdf,这样便于管理文件,同时php程序也不用去调用任何组件,两个程序没有半点关系。

程序已经在服务器上跑了一个月了,没发生任何错误!!完美~~~~
在这里插入图片描述

源码很少,用到了3个组件:Aspose.Words.dll、Aspose.Cells.dll、Aspose.Slides.dll,以下是源码:下载地址在最下面!!

using System;
using System.IO;
using System.Windows.Forms;
using Aspose.Words;
using Aspose.Cells;
using Aspose.Slides;
using System.Threading;
using System.Runtime.InteropServices;

namespace Office2PDF
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            StartBtn.Visible = true;
            StopBtn.Visible = false;
            // 创建日志目录
            if (!Directory.Exists(LogFilePath))
            {
                Directory.CreateDirectory(LogFilePath);
            }
            // 初始化控件值
            WatchPath.Text = appsetting.Default.WatchPath;
            ExcludeFolder.Text = appsetting.Default.ExcludeFolder;
            WordCheckBox.Checked = appsetting.Default.WordCheckBox;
            ExcelCheckBox.Checked = appsetting.Default.ExcelCheckBox;
            PowerpointCheckBox.Checked = appsetting.Default.PowerpointCheckBox;
        }

        private String LogFilePath = Application.StartupPath + "\\log";

        private void ExitBtn_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        private void SelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            WatchPath.Text = path.SelectedPath;
            appsetting.Default.WatchPath = path.SelectedPath;
            appsetting.Default.Save();
        }

        public void WriteMessage(string msg)
        {
            var path = "log\\"+DateTime.Now.ToString("yyyyMMdd") + ".log";
            if (!File.Exists(path)){
                var fsc = new FileStream(path, FileMode.Create, FileAccess.Write);
                fsc.Close();
            }
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.End);
                    sw.WriteLine("{0}", "[" + GetNowTime() + "]:" +msg, DateTime.Now);
                    sw.Flush();
                }
            }
        }

        private void StartBtn_Click(object sender, EventArgs e)
        {
            StartBtn.Visible = false;
            StopBtn.Visible = true;
            var wPath = WatchPath.Text;
            fileSystemWatcher.Path = wPath;
            fileSystemWatcher.Created += OnCreated;
            fileSystemWatcher.EnableRaisingEvents = true;
        }

        private void LogBtn_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(LogFilePath);
        }

        private void StopBtn_Click(object sender, EventArgs e)
        {
            StartBtn.Visible = true;
            StopBtn.Visible = false;
            fileSystemWatcher.EnableRaisingEvents = false;
        }

        private void OnCreated(object source, FileSystemEventArgs e)
        {
            var msg = e.FullPath;
            var ext = Path.GetExtension(e.FullPath);
            var path = Path.GetDirectoryName(e.FullPath);
            bool isExclude = false;
            // 处理排除目录
            string[] arr = new string[ExcludeFolder.Lines.Length];
            for (int i = 0; i < ExcludeFolder.Lines.Length; i++)
            {
                arr[i] = ExcludeFolder.Lines[i];
                if (ExcludeFolder.Lines[i].Length != 0)
                {
                    if (path.IndexOf(ExcludeFolder.Lines[i]) > 0)
                    {
                        isExclude = true;
                    }
                }
            }
            if (!isExclude)
            {
                if (WordCheckBox.Checked)
                {
                    if (ext == ".doc" || ext == ".docx")
                    {
                        Thread.Sleep(1000);
                        var doc = new Document(@e.FullPath);
                        doc.Save(@e.FullPath + ".pdf", Aspose.Words.SaveFormat.Pdf);
                        WriteMessage(msg);
                    }
                }
                if (ExcelCheckBox.Checked)
                {
                    if (ext == ".xls" || ext == ".xlsx")
                    {
                        Thread.Sleep(1000);
                        var xls = new Workbook(@e.FullPath);
                        xls.Save(@e.FullPath + ".pdf", Aspose.Cells.SaveFormat.Pdf);
                        WriteMessage(msg);
                    }
                }
                if (PowerpointCheckBox.Checked)
                {
                    if (ext == ".ppt" || ext == ".pptx")
                    {
                        Thread.Sleep(1000);
                        var ppt = new Presentation(@e.FullPath);
                        ppt.Save(@e.FullPath + ".pdf", Aspose.Slides.Export.SaveFormat.Pdf);
                        WriteMessage(msg);
                    }
                }
            }
        }

        private void ExcludeFolder_TextChanged(object sender, EventArgs e)
        {
            appsetting.Default.ExcludeFolder = ExcludeFolder.Text;
            appsetting.Default.Save();
        }

        private void WordCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            appsetting.Default.WordCheckBox = WordCheckBox.Checked;
            appsetting.Default.Save();
        }

        private void ExcelCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            appsetting.Default.ExcelCheckBox = ExcelCheckBox.Checked;
            appsetting.Default.Save();
        }

        private void PowerpointCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            appsetting.Default.PowerpointCheckBox = PowerpointCheckBox.Checked;
            appsetting.Default.Save();
        }

        private static string GetNowTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        private void FreeTimer_Tick(object sender, EventArgs e)
        {
            ClearMemory();
        }
        // 释放内存
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                MainForm.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
    }
}

项目下载地址:
Office2PDF v1.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

୧⍢⃝୨ LonelyCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值