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

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

由于新开发的信息系统,原来旧版的信息系统,在查看文件时,都需要下载到本地,然后在打开查看,这样比较繁琐,所以在新版信息系统里,用了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

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
您可以使用 C# 的 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,将 WordExcel 文件转换为 PDF 格式,然后使用第三方的 PDF 打印工具批量打印这些 PDF 文件。以下是具体步骤: 1. 引用 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,如果您使用的是 Visual Studio,可以在“解决方案资源管理器”中右键单击项目名称,选择“添加”->“引用”->“COM”选项卡,然后勾选“Microsoft Word xx.x Object Library”和“Microsoft Excel xx.x Object Library”; 2. 创建 WordExcel 应用程序对象,打开需要转换的 WordExcel 文件; 3. 使用应用程序对象的“ExportAsFixedFormat”方法将 WordExcel 文件转换为 PDF 格式; 4. 关闭 WordExcel 文件,销毁应用程序对象; 5. 下载并安装一个第三方的 PDF 打印工具,如 Adobe Acrobat Reader 或 Foxit Reader; 6. 使用 C# 调用第三方的 PDF 打印工具,将需要打印的 PDF 文件添加到打印列表中; 7. 配置打印选项,如打印机、打印质量等; 8. 点击“打印”按钮,即可批量打印 PDF 文件。 需要注意的是,在转换 WordExcel 文件PDF 格式时,可能会出现格式错位、字体不一致等问题。建议在转换前进行一次预览,确保转换后的 PDF 文件符合预期。同时,如果您打算开发一个批量打印工具,还需要考虑如何对文件进行批量处理、如何处理转换和打印过程中可能发生的异常等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

୧⍢⃝୨ LonelyCoder

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

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

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

打赏作者

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

抵扣说明:

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

余额充值