2016-07-26 7 views
-1

Ich habe viele Beispiele online über das Konvertieren von Word (.docx) -Datei in PDF-Datei gefunden.Konvertieren von Word in PDF im Hintergrundprozess entweder über C# oder IronPython

Es funktioniert gut, wenn ich von UI-Thread ausführen. Aber in dem Moment führe ich es im Hintergrund Prozess. dann scheitert es. Gibt es eine Möglichkeit, Word über Hintergrundprozessausführung in PDF zu konvertieren?

Im Folgenden finden Sie den IronPython- und C# -Code, der im UI-Thread funktioniert.

Ironpython:

import sys 
import clr 
import System 
from System.Text import StringBuilder 
from System.IO import DirectoryInfo, File, FileInfo, Path, StreamWriter 

clr.AddReference("Microsoft.Office.Interop.Word") 
import Microsoft.Office.Interop.Word as Word 

def ConvertWordToPDF(wordDocFullPath): 
    """ 
    <Script> 
    <Author>SNI</Author> 
    <Description>Converts Word document to PDF.</Description> 
    <Parameters> 
    <Parameter name="wordDocFullPath" type="string">Word document full path.</Parameter> 
    </Parameters> 
    <ReturnValue type="string">PDF full path</ReturnValue> 
    </Script> 
    """ 
    wordDocInfo = FileInfo(wordDocFullPath) 
    pdfFullPath = Path.Combine(wordDocInfo.DirectoryName, wordDocInfo.Name.TrimEnd(wordDocInfo.Extension.ToCharArray()) + '.pdf') 

    word_application = Word.ApplicationClass() 
    word_application.visible = False 

    wordDocument = word_application.Documents.Open(wordDocFullPath); 
    if wordDocument: 
     wordDocument.ExportAsFixedFormat(pdfFullPath, Word.WdExportFormat.wdExportFormatPDF); 
     wordDocument.Close() 
     word_application.Quit() 
     word_application = None 
    else: 
     print 'failed to initialize word document' 

    print pdfFullPath 
    return pdfFullPath` 

C# -Code:

public string Convert(string wordDocPath) 
{ 
    string pdfPath = string.Empty; 

    try 
    { 
     Microsoft.Office.Interop.Word.Application word = null; 
     Document doc = null; 

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

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

      Thread.Sleep(5000); 

      word.Visible = false; 
      word.ScreenUpdating = false; 
      doc = word.Documents.Open(wordDocPath); 
      pdfPath = wordDocPath.Replace(".docx", ".pdf"); 

      doc.ExportAsFixedFormat(
         pdfPath, 
         Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, 
         OptimizeFor: Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, 
         BitmapMissingFonts: true, DocStructureTags: false); 

      ((Microsoft.Office.Interop.Word._Document)doc).Close(); 
      ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
     } 
     catch 
     { 
      if (doc != null) 
      { 
       ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); 
      } 

      if (word != null) 
      { 
       ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
      } 
      throw; 
     } 
    } 
    catch (Exception ex) 
    { 
     var st = new StackTrace(ex, true); 
     // Get the top stack frame 
     var frame = st.GetFrame(0); 
     // Get the line number from the stack frame 
     var line = frame.GetFileLineNumber(); 

     throw new Exception("Line Number: " + line.ToString() + " " + ex.ToString()); 
    } 
    return pdfPath; 
} 
+0

Nun, was scheitert in der C# -Code? IST der Fehler etwas damit zu tun "kann nicht auf Objekt von einem anderen Thread zugreifen, dann wurde es erstellt"? – noone392

+0

von C# es wirft Objektreferenz nicht auf eine Instanz des Objektfehlers gesetzt. weiter, wenn ich mit Python getestet, konnte ich in der Zeile, wo es bricht, in der Lage, Null Dokument Objekt unter Zeile doc = Word.Documents.Open (WordDocPath); aufgrund der Ausführung im Hintergrund ohne UI-Thread. –

Antwort

0

Got unten Antwort von meinem Kollegen Anders kennen.

Sekunden antworten hier Open and modify Word Document sagt Microsoft unterstützt nicht unbeaufsichtigte Authentifizierung auf diese Weise. Es schlägt auch http://freeword.codeplex.com/

mit habe ich gerade festgestellt, dass dieser Skript funktioniert - auch von einem Job/Hintergrund-Prozess:

Obwohl dies keine freie Software ist, aber es funktioniert auf Hintergrundprozess. Es kann leicht auch nach C# portiert werden, da es eine .net dll ist.

import clr

clr.AddReferenceToFileAndPath (R "C: \ Programme (x86) \ E-iceblue \ Spire.Doc-FE \ Bin \ NET4.0 \ Spire.Doc.dll")

von Spire.Doc import *

von Spire.Doc.Documents importieren *

von System.IO Import Directory, Datei, Fileinfo, Pfad

def ConvertWordToPDFUsingSPIRE (wordD ocFullPath):

""" 

<Script> 

<Author>SNI</Author> 

<Description>Converts Word document to PDF.</Description> 

<Parameters> 

<Parameter name="wordDocFullPath" type="string">Word document full path.</Parameter> 

</Parameters> 

<ReturnValue type="string">PDF full path</ReturnValue> 

</Script> 

""" 

wordDocInfo = FileInfo(wordDocFullPath) 

pdfFullPath = Path.Combine(wordDocInfo.DirectoryName, wordDocInfo.Name.TrimEnd(wordDocInfo.Extension.ToCharArray()) + '.pdf') 




document = Document(); 

document.LoadFromFile(wordDocFullPath); 




# Convert Word to PDF 



document.SaveToFile(pdfFullPath, FileFormat.PDF); 
Verwandte Themen