2014-10-08 8 views
-2

Я пытаюсь преобразовать файл doc или docx в PDF с помощью visual studio 2013. Язык C#. Я пытался отладки и я думаю, что у меня есть проблемы со следующей частью коды:C#. Преобразование Doc в PDF

public static void Main(string[] args) 
    { 
     if (args.Count() > 1) 
     { 
      translate.ConvertAllWordFilesToPdf(args[0], args[1]); 
     } 

    } 

Я не получаю никаких ошибок. Я получаю это выходное сообщение: Программа '[9240] Conversion.vshost.exe' вышла с кодом 0 (0x0).

Благодарим за помощь.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.IO; 
using System.Text; 
using Microsoft.Office.Interop.Word; 

namespace Conversion 
{ 
public static class Program 
{ 
    public static void Main(string[] args) 
    { 
     if (args.Count() > 1) 
     { 
      translate.ConvertAllWordFilesToPdf(args[0], args[1]); 
     } 

    } 

    public class translate 
    { 

     public static void ConvertAllWordFilesToPdf(string WordFilesLocation, string PdfFilesLocation) 
     { 
      Document doc = null; 


      object oMissing = System.Reflection.Missing.Value; 
      Microsoft.Office.Interop.Word.Application word = null; 

      try 
      { 

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


       DirectoryInfo dirInfo = new DirectoryInfo(WordFilesLocation); 

       FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); 

       if (wordFiles.Length > 0) 
       { 
        word.Visible = false; 
        word.ScreenUpdating = false; 
        string sourceFile = ""; 
        string destinationFile = ""; 
        try 
        { 
         foreach (FileInfo wordFile in wordFiles) 
         { 

          Object filename = (Object)wordFile.FullName; 

          sourceFile = wordFile.Name; 
          destinationFile = ""; 


          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 = null; 

          if (wordFile.FullName.ToUpper().Contains(".DOCX")) 
          { 
           outputFileName = wordFile.FullName.Replace(".docx", ".pdf"); 
           destinationFile = sourceFile.Replace(".docx", ".pdf"); 

          } 
          else 
          { 
           outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); 
           destinationFile = sourceFile.Replace(".doc", ".pdf"); 
          } 

          sourceFile = WordFilesLocation + @"C:\Source" + destinationFile; 
          destinationFile = PdfFilesLocation + @"C:\Destination" + destinationFile; 

          object fileFormat = WdSaveFormat.wdFormatPDF; 


          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; 


          if (System.IO.File.Exists(destinationFile)) 
          { 
           System.IO.File.Replace(sourceFile, destinationFile, null); 
          } 
          else 
          { 
           System.IO.File.Move(sourceFile, destinationFile); 
          } 

          Console.WriteLine("Success:" + "SourceFile-" + outputFileName.ToString() + " DestinationFile-" + destinationFile); 

         } 


         ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
         word = null; 
        } 
        catch (Exception ex) 
        { 

         Console.WriteLine("Fail:" + "SourceFile-" + sourceFile + " DestinationFile-" + destinationFile + "#Error-" + ex.Message); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Error occured while processing"); 
       Console.WriteLine(ex.Message); 
      } 
      finally 
      { 
       if (doc != null) 
       { 
        ((_Document)doc).Close(ref oMissing, ref oMissing, ref oMissing); 
        doc = null; 

       } 
       if (word != null) 
       { 
        ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
        word = null; 
       } 
      } 
     } 
    } 
    } 
} 
+0

Можете ли вы немного сузить его? Что значит «не работает»? – Matthew

+3

Вы отметили это как 'asp.net', но вы используете Office Interop. Они плохо работают вместе. Microsoft [специально рекомендует против этого] (http://support2.microsoft.com/kb/257757). Вероятно, вы столкнетесь со всеми проблемами, если продолжите использовать библиотеки Interop в среде ASP.NET. – mason

+0

Не конвертируйте документ в pdf. Не получается результата. –

ответ

0

Я заметил очень интересный кусок кода:

sourceFile = WordFilesLocation + @"C:\Source" + destinationFile; 
destinationFile = PdfFilesLocation + @"C:\Destination" + destinationFile; 

Попробуйте удалить @"C:\Source". Я удалил его, и код работал на моем компьютере.

Кроме того, я не уверен, следует ли добавлять @"\" для некоторых строк местоположения (не заканчивая «\»). Быть осторожен.

+0

Символ «@» сообщает компилятору избегать всех символов в данной строке. Это совсем не обязательно, но вам может потребоваться изменить содержимое строки соответствующим образом, если вы ее не используете. –

+0

Вместо @ "C: \ Source" я положил "\\" Но он все еще не работает. –

+0

Я получаю это выходное сообщение: программа '[9240] Conversion.vshost.exe' вышла с кодом 0 (0x0). –