线程化例程将doc转换为PDF

时间:2016-01-18 15:38:45

标签: c# multithreading

是新线程并且已经启动了2线程应用程序,它运行基本的Doc to PDF转换方法。客户端具有要转换的Word 2003文件。

然而,代码运行它似乎打开一个单词实例到屏幕,它确实打开了一个框和进度条,然后我进行了线程化。

我现在应该以不同的方式处理单词吗?

我试图通过运行多个线程来处理处理器,并加快转换30000个doc文件。

我不打算使用任何第三方工具,只需从网站上的帖子中说出Word就是最好的转换。

主要

 MyThread thr1 = new MyThread();
 MyThread thr2 = new MyThread();

 Thread tid1 = new Thread(new ThreadStart(thr1.Thread1));
 Thread tid2 = new Thread(new ThreadStart(thr2.Thread1));

 tid1.Name = "Thread 1";
 tid2.Name = "Thread 2";

 tid1.Start();
 tid2.Start();

Thread1代码

     Word.Application word = new Microsoft.Office.Interop.Word.Application();

     // C# doesn't have optional arguments so we'll need a dummy value
     object oMissing = System.Reflection.Missing.Value;

     // Get list of Word files in specified directory
     DirectoryInfo dirInfo = new DirectoryInfo(@"C:\ConvertToPDF\Docs");
     FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

     Thread thr = Thread.CurrentThread;

     if (thr.Name == "Thread 1")
        {
        var orderedSort = wordFiles.OrderBy(f => f.CreationTime);
        }
     else
        {
        var orderedSort = wordFiles.OrderByDescending(f => f.CreationTime);
        }

     word.Visible = false;
     word.ScreenUpdating = false;

     foreach (FileInfo wordFile in wordFiles)
        {
       // Cast as Object for word Open method
       Object filename = (Object)wordFile.FullName;

      // Use the dummy value as a placeholder for optional arguments
      Document doc = word.Documents.Open(ref filename, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);
      doc.Activate();

      object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
      object fileFormat = WdSaveFormat.wdFormatPDF;

      // Save document into PDF Format
      doc.SaveAs(ref outputFileName,
                ref fileFormat, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing);

      object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
         ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
            doc = null;
        }

        // word has to be cast to type _Application so that it will find
        // the correct Quit method.
        ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
        word = null;

2 个答案:

答案 0 :(得分:1)

不要在服务器上使用Word。你会度过一段美好的时光。

使用OpenXML SDK:

https://www.microsoft.com/en-us/download/details.aspx?id=5124

答案 1 :(得分:1)

在下面的问题中查看我在答案中使用的代码:

Wordapp not closing in Thread or Parallel process