private async void ConvertButton_Click(object sender, RoutedEventArgs e) { if (!_currentSettings.IsValid()) { _showError("All settings are required"); return; } try { ConversionEngine.AddJobs(ConversionJob.Create(SourceTextBox.Text, OutputTextBox.Text, _currentSettings)); ConversionEngine.CreateScriptFile(); ProgressBar.IsIndeterminate = true; var startTime = DateTime.Now; await ConversionEngine.Run(); var endTime = DateTime.Now; ProgressBar.IsIndeterminate = false; System.Windows.MessageBox.Show($"Conversion job started at {startTime.ToString()}{Environment.NewLine}Finished at {endTime.ToString()}", "Conversion finished", MessageBoxButton.OK, MessageBoxImage.Information); } catch (ArgumentOutOfRangeException ex) { _showError(ex.Message + Environment.NewLine + ex.ParamName); } catch (DirectoryNotFoundException ex) { _showError(ex.Message); } catch (FileNotFoundException ex) { _showError(ex.Message + Environment.NewLine + ex.FileName); } }
/// <summary> /// Convert document to PDF /// </summary> public void ConvertDocToPDF(SPListItem listItem) { try { SharePointHelper spHelper = new SharePointHelper(); string WordAutoSvc = spHelper.GetRCRSettingsItem("AutomationServices").ToString(); //Variables used for PDF conversions ConversionJobSettings jobSettings; ConversionJob pdfConversionJob; string wordFile; //Source Word file string pdfFile; //target destination PDF file // Initialize the conversion settings. jobSettings = new ConversionJobSettings(); jobSettings.OutputFormat = SaveFormat.PDF; // Create the conversion job using the settings. pdfConversionJob = new ConversionJob(WordAutoSvc, jobSettings); //Set the credentials to use when running the conversion job. pdfConversionJob.UserToken = SPContext.Current.Web.CurrentUser.UserToken; // Set the file names to use for the source Word document and the destination PDF document. wordFile = SPContext.Current.Web.Url + "/" + listItem.Url; if (IsFileTypeDoc(listItem.File, "docx")) { pdfFile = wordFile.Replace(".docx", ".pdf"); } else if (IsFileTypeDoc(listItem.File, "doc")) { pdfFile = wordFile.Replace(".doc", ".pdf"); } else { pdfFile = ""; } if (pdfFile.Length > 0) { // Add the file conversion to the conversion job. pdfConversionJob.AddFile(wordFile, pdfFile); // Add the conversion job to the Word Automation Services conversion job queue. // The conversion does not occurimmediately but is processed during the next run of the document conversion job. pdfConversionJob.Start(); } spHelper = null; } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ClassName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "ConvertDocToPDF - " + ex.Message, ex.StackTrace); } }
public bool Start() { stateBar.Cancel += (sender, e) => CancelCurrentJob(); stateBar.ManageJobs += (sender, e) => ManageJobs(); Config.EventsBroker.ConvertVideoFilesEvent += (inputFiles, encSettings) => { ConversionJob job = new ConversionJob(inputFiles, encSettings); AddJob(job); }; return(true); }
// Активация архивирования protected void ArchiveItems_Click(object sender, EventArgs e) { // адрес сайта String sharePointSite = "http://vizatech.westeurope.cloudapp.azure.com/sites/team/"; // получаем контекст списка SPSite oSite = new SPSite(sharePointSite); SPWeb oWeb = oSite.OpenWeb(); SPList list = oWeb.Lists["Doc2"]; // получает набор АйДи для архивации char[] delimiterChars = { ' ', ',', '.', ':', '|' }; string[] SelectedItemIDs = ItemIDs.Text.Split(delimiterChars); // Создаем Отчет об орхивировании для каждого отобранного Айтема foreach (string ID in SelectedItemIDs) { int SelectedItemIDint = 0; try { SelectedItemIDint = Int32.Parse(ID); } catch { } if ((SelectedItemIDint > 0)) { // полчаем контекст Айтема SPListItem SelectedItem = list.Items.GetItemById(SelectedItemIDint); // передаем данные методу создания отчета CreateDocument(SelectedItem); } } oSite = new SPSite(sharePointSite); oWeb = oSite.OpenWeb(); oWeb.AllowUnsafeUpdates = true; // получаем контекст Службы конвертации ConversionJob myJob = new ConversionJob("Word Automqtion Service"); // задаем параметры конвертации myJob.Settings.OutputFormat = SaveFormat.PDF; myJob.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; myJob.UserToken = oWeb.CurrentUser.UserToken; // задаем от куда брать и куда переносить файлы SPList inputLibrary = oWeb.Lists["QueueLib"]; SPList outputLibrary = oWeb.Lists["ArchiveLib"]; myJob.AddLibrary(inputLibrary, outputLibrary); myJob.Start(); //ClearLibrary(inputLibrary); // возвращаем управление вызвавшему сайту Response.Redirect(sharePointSite); }
private OASResponse StartWordConversion(OASModels.ConversionSettings settings, SPUserToken userToken) { OASResponse oasResponse = new OASResponse(); using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken))) { using (SPWeb web = site.OpenWeb()) { try { web.AllowUnsafeUpdates = true; byte[] input = Convert.FromBase64String(settings.Content); SPFolder lib = GetOASLibrary(web); //add source file to library string source = Guid.NewGuid().ToString(); SPFile srcfile = lib.Files.Add(source, input, true); string dest = source + EXTENSION; //Set up the job ConversionJobSettings set = FillWordConversionOptions(settings.Options); set.OutputFormat = SaveFormat.PDF; ConversionJob syncConv = new ConversionJob(ConfigurationManager.AppSettings["WASName"], set); if (userToken != null) { syncConv.UserToken = userToken; } syncConv.AddFile(web.Url + "/" + lib.Url + "/" + source, web.Url + "/" + lib.Url + "/" + dest); syncConv.Start(); // put file to the processing list AddFileToList(web, syncConv.JobId.ToString(), dest, DocType.DOCX); oasResponse.FileId = syncConv.JobId.ToString(); oasResponse.ErrorCode = OASErrorCodes.Success; } catch (Exception ex) { oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert; oasResponse.Message = ex.Message; } } } return(oasResponse); }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); //Verify the document added is a Word Document // before starting the conversion. if (properties.ListItem.Name.Contains(".docx") || properties.ListItem.Name.Contains(".doc")) { //Variables used by the sample code. ConversionJobSettings jobSettings; ConversionJob pdfConversion; string wordFile; string pdfFile; //Initialize the conversion settings. jobSettings = new ConversionJobSettings(); jobSettings.OutputFormat = SaveFormat.PDF; //Create the conversion job using the settings. pdfConversion = new ConversionJob("Word Automation Services", jobSettings); //Set the credentials to use when running the conversion job. pdfConversion.UserToken = properties.Web.CurrentUser.UserToken; //Set the file names to use for the source Word document // and the destination PDF document. wordFile = properties.WebUrl + "/" + properties.ListItem.Url; if (properties.ListItem.Name.Contains(".docx")) { pdfFile = wordFile.Replace(".docx", ".pdf"); } else { pdfFile = wordFile.Replace(".doc", ".pdf"); } //Add the file conversion to the Conversion Job. pdfConversion.AddFile(wordFile, pdfFile); //Add the Conversion Job to the Word Automation Services // conversion job queue. //The conversion will not take place immeditately but // will be processed during the next run of the // Document Conversion job. pdfConversion.Start(); } }
protected void ConvertDotxToDocx(SPWeb web, string inputFile, string outputFile) { string wordAutomationServiceName = "Word Automation Service"; var conversionJob = new ConversionJob(wordAutomationServiceName); conversionJob.UserToken = web.CurrentUser.UserToken; conversionJob.Name = "TTK.Document.Conversion.CustomerRecord." + inputFile; conversionJob.Settings.OutputFormat = SaveFormat.PDF; conversionJob.UserToken = web.Site.UserToken; conversionJob.AddFile(inputFile, outputFile); conversionJob.Start(); }
public RenderingJobsManager(IMultimediaToolkit multimediaToolkit, IGUIToolkit guiToolkit) { this.guiToolkit = guiToolkit; this.multimediaToolkit = multimediaToolkit; this.stateBar = guiToolkit.MainWindow.RenderingStateBar; capturer = multimediaToolkit.GetFramesCapturer(); jobs = new List <Job>(); pendingJobs = new List <Job>(); stateBar.Cancel += (sender, e) => CancelCurrentJob(); stateBar.ManageJobs += (sender, e) => ManageJobs(); guiToolkit.MainWindow.ConvertVideoFilesEvent += delegate(List <MediaFile> inputFiles, EncodingSettings encSettings) { ConversionJob job = new ConversionJob(inputFiles, encSettings); AddJob(job); };; }
void LoadConversionJob(ConversionJob job) { videoEditor = App.Current.MultimediaToolkit.GetVideoEditor(); videoEditor.EncodingSettings = job.EncodingSettings; videoEditor.Progress += OnProgress; videoEditor.Error += OnError; foreach (MediaFile file in job.InputFiles) { PlaylistVideo video = new PlaylistVideo(file); Log.Debug("Convert video " + video.File.FilePath); videoEditor.AddSegment(video.File.FilePath, 0, -1, 1, "", video.File.HasAudio, new Area()); } videoEditor.Start(); }
protected void SubmitButton_Click(object sender, EventArgs e) { ConversionJob myJob = new ConversionJob("Word Automqtion Service"); myJob.Settings.OutputFormat = SaveFormat.PDF; myJob.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; myJob.UserToken = SPContext.Current.Web.CurrentUser.UserToken; SPWeb myWebSite = SPContext.Current.Web; SPList inputLibrary = myWebSite.Lists["Entrance"]; SPList outputLibrary = myWebSite.Lists["Transformed"]; myJob.AddLibrary(inputLibrary, outputLibrary); myJob.Start(); }
void ExecuteConversion() { EncodingSettings encSettings; EncodingQuality qual; TreeIter iter; VideoStandard std; uint fps_n, fps_d; sizecombobox.GetActiveIter(out iter); std = (VideoStandard)stdStore.GetValue(iter, 1); bitratecombobox.GetActiveIter(out iter); qual = bitStore.GetValue(iter, 1) as EncodingQuality; var rates = new HashSet <uint> (Files.Select(f => (uint)f.Fps)); if (rates.Count == 1) { fps_n = rates.First(); fps_d = 1; } else { fps_n = App.Current.Config.FPS_N; fps_d = App.Current.Config.FPS_D; } if (fps_n == 50) { fps_n = 25; } else if (fps_n == 60) { fps_n = 30; } encSettings = new EncodingSettings(std, EncodingProfiles.MP4, qual, fps_n, fps_d, mediafilechooser1.CurrentPath, true, false, 0, null); EncodingSettings = encSettings; ConversionJob job = new ConversionJob(Files, EncodingSettings); App.Current.JobsManager.Add(job); Respond(ResponseType.Ok); }
public Guid ConvertDocuments(SPSite spSite, SPWeb spWeb, ArrayList files, DocSaveFormat docSaveFormat, DocSaveBehaviour docSaveBehaviour) { SaveFormat savFormat = GetSaveFormat(docSaveFormat); SaveBehavior savBehaviour = getSaveBehavior(docSaveBehaviour); const string wordAutomationServiceName = "Word Automation Services"; var job = new ConversionJob(wordAutomationServiceName) {UserToken = spSite.UserToken}; job.Settings.UpdateFields = true; job.Settings.OutputFormat = savFormat; job.Settings.OutputSaveBehavior = savBehaviour; job.Settings.AddThumbnail = true; foreach (string file in files) { job.AddFile(spWeb.Url + "/" + SourceLibrary + "/" + file, spWeb.Url + "/" + DestinationLibrary + "/" + Path.GetFileNameWithoutExtension(file) + Extension); } job.Start(); _status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null); return job.JobId; }
static void Main(string[] args) { string siteUrl = "http://localhost"; // If you manually installed Word automation services, then replace the name // in the following line with the name that you assigned to the service when // you installed it. string wordAutomationServiceName = "Word Automation Services"; using (SPSite spSite = new SPSite(siteUrl)) { ConversionJob job = new ConversionJob(wordAutomationServiceName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.PDF; job.AddFile(siteUrl + "/Shared%20Documents/Test.docx", siteUrl + "/Shared%20Documents/Test.pdf"); job.Start(); } }
public ActionResult <ConversionJob> CreatePdfAsync([FromBody] PdfParameters parameters) { var converionId = Guid.NewGuid().ToString(); var thread = new Thread(new ThreadStart(() => { CreatePdfImpl(converionId, parameters).Wait(); })); thread.Start(); var conversionJob = new ConversionJob(converionId, thread); lock (Jobs) { Jobs.Add(converionId, conversionJob); } return(conversionJob); }
private void LoadConversionJob(ConversionJob job) { videoConverter = multimediaToolkit.GetVideoConverter(job.EncodingSettings.OutputFile); videoConverter.Progress += OnProgress; videoConverter.EncodingSettings = job.EncodingSettings; videoConverter.Error += OnError; foreach (MediaFile file in job.InputFiles) { videoConverter.AddFile(file.FilePath, file.Length); } try { videoConverter.Start(); } catch (Exception ex) { videoConverter.Cancel(); job.State = JobState.Error; Log.Exception(ex); Log.Error("Error rendering job: ", job.Name); guiToolkit.ErrorMessage(Catalog.GetString("Error rendering job: ") + ex.Message); } }
private void ExecuteConversionJob(object parameter) { ConversionJob conversionJob = parameter as ConversionJob; if (conversionJob == null) { throw new System.ArgumentException("The parameter must be a conversion job.", "parameter"); } if (conversionJob.State != ConversionJob.ConversionState.Ready) { Debug.LogError("Fail to execute conversion job."); return; } try { conversionJob.StartConvertion(); } catch (Exception exception) { Debug.LogError("Failure during conversion: {0}", exception.ToString()); } }
/// <summary> /// Timer job to convert doc to PDF /// </summary> /// <param name="srcFile"></param> /// <param name="dstFile"></param> /// <returns></returns> public bool PDFConvertJob(string srcFile, string dstFile) { try { //create references to the Word Services. var wdProxy = (WordServiceApplicationProxy)SPServiceContext.Current.GetDefaultProxy(typeof(WordServiceApplicationProxy)); var conversionJob = new ConversionJob(wdProxy); conversionJob.UserToken = SPContext.Current.Web.CurrentUser.UserToken; conversionJob.Name = "PDF Conversion Job " + DateTime.Now.ToString("hhmmss"); conversionJob.Settings.OutputFormat = SaveFormat.PDF; conversionJob.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; conversionJob.AddFile(srcFile, dstFile); conversionJob.Start(); return(conversionJob.Started); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ClassName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "PDFConverJob - " + ex.Message, ex.StackTrace); return(false); } }
private void ConvertFiles() { // Prepare conversions. for (int index = 0; index < this.ConvertionJobs.Count; index++) { this.ConvertionJobs[index].PrepareConversion(); } // Convert! Thread[] jobThreads = new Thread[this.numberOfConversionThread]; while (true) { // Compute conversion flags. ConversionFlags conversionFlags = ConversionFlags.None; bool allJobAreFinished = true; for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) { ConversionJob conversionJob = this.conversionJobs[jobIndex]; allJobAreFinished &= !(conversionJob.State == ConversionJob.ConversionState.Ready || conversionJob.State == ConversionJob.ConversionState.InProgress); if (conversionJob.State == ConversionJob.ConversionState.InProgress) { conversionFlags |= conversionJob.StateFlags; } } if (allJobAreFinished) { break; } // Start job if possible. for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) { ConversionJob conversionJob = this.conversionJobs[jobIndex]; if (conversionJob.State == ConversionJob.ConversionState.Ready && conversionJob.CanStartConversion(conversionFlags)) { // Find a thread to execute the job. Thread jobThread = null; for (int threadIndex = 0; threadIndex < jobThreads.Length; threadIndex++) { Thread thread = jobThreads[threadIndex]; if (thread == null || !thread.IsAlive) { jobThread = Helpers.InstantiateThread(conversionJob.GetType().Name, this.ExecuteConversionJob); jobThreads[threadIndex] = jobThread; break; } } if (jobThread != null) { jobThread.Start(conversionJob); while (conversionJob.State == ConversionJob.ConversionState.Ready) { Debug.Log("Wait the launch of the conversion thread before launching any other thread."); Thread.Sleep(20); } } break; } } Thread.Sleep(50); } if (this.Settings.ExitApplicationWhenConversionsFinished) { bool allConversionsSucceed = true; for (int index = 0; index < this.conversionJobs.Count; index++) { allConversionsSucceed &= this.conversionJobs[index].State == ConversionJob.ConversionState.Done; } if (this.cancelAutoExit) { return; } if (allConversionsSucceed) { float remainingTime = this.Settings.DurationBetweenEndOfConversionsAndApplicationExit; while (remainingTime > 0f) { if (this.OnApplicationTerminate != null) { this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); } System.Threading.Thread.Sleep(1000); remainingTime--; if (this.cancelAutoExit) { return; } } if (this.OnApplicationTerminate != null) { this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); } Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); } } }
static void Main(string[] args) { Console.WriteLine("OPG DocStorageConverter"); Console.WriteLine(""); Console.WriteLine("Connecting to:\t\t" + Settings.siteUrl); using (SPSite spSite = new SPSite(Settings.siteUrl)) { SPFolder folderToConvert = spSite.RootWeb.GetFolder(Settings.fileconvert); ConversionJob job = new ConversionJob(Settings.wordAutomationServiceName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.PDF; job.Settings.FixedFormatSettings.UsePDFA = true; foreach (SPFile file in folderToConvert.Files) { if (Files.HasExtension(file.Name, new string[] { ".docx", ".docm", ".dotx", ".dotm", ".doc", ".dot", ".rtf", ".mht", ".mhtml", ".xml" })) { string filePath = (Settings.siteUrl + "/" + file.Url); Console.WriteLine("Found:\t\t\t" + filePath); using (SPWeb web = spSite.OpenWeb()) { if (web.GetFile(filePath).Exists) { Console.WriteLine("Already Exists:\t\t" + Files.StripExtension(filePath) + ".pdf"); Console.WriteLine("Deleting:\t\t" + Files.StripExtension(filePath) + ".pdf"); SPFile eFile = web.GetFile(Files.StripExtension(filePath) + ".pdf"); eFile.Delete(); eFile.Update(); } } job.AddFile(filePath, Files.StripExtension(filePath) + ".pdf"); } } try { job.Start(); } catch (InvalidOperationException) { Console.WriteLine("Done:\t\t\tNo files to convert"); return; } Console.WriteLine("\t\t\tConversion job started"); ConversionJobStatus status = new ConversionJobStatus(Settings.wordAutomationServiceName, job.JobId, null); Console.WriteLine("Job length:\t\t" + status.Count); while (true) { Thread.Sleep(5000); status = new ConversionJobStatus(Settings.wordAutomationServiceName, job.JobId, null); if (status.Count == status.Succeeded + status.Failed) { Console.WriteLine("Completed:\t\tSuccessful: " + status.Succeeded + ", Failed: " + status.Failed); ReadOnlyCollection <ConversionItemInfo> failedItems = status.GetItems(ItemTypes.Failed); foreach (ConversionItemInfo failedItem in failedItems) { Console.WriteLine("Failed converting:\t" + failedItem.InputFile); Console.WriteLine(failedItem.ErrorMessage); } Console.WriteLine("\t\t\tSetting meta on files that successfully converted"); ReadOnlyCollection <ConversionItemInfo> convertedItems = status.GetItems(ItemTypes.Succeeded); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = spSite.OpenWeb()) { web.AllowUnsafeUpdates = true; foreach (ConversionItemInfo convertedItem in convertedItems) { SPFile inFile = web.GetFile(convertedItem.InputFile); SPFile outFile = web.GetFile(convertedItem.OutputFile); try { SPListItem inListItem = inFile.Item; SPListItem outListItem = outFile.Item; Console.WriteLine("Set metadata on:\t" + outFile.Url); foreach (SPField field in inListItem.Fields) { try { if (outListItem.Fields.ContainsField(field.InternalName) == true && field.ReadOnlyField == false && field.InternalName != "Attachments" && field.InternalName != "Name") { outListItem[field.InternalName] = inListItem[field.InternalName]; Console.WriteLine("Setting field:\t\t" + field.InternalName); } } catch (Exception e) { Console.WriteLine("Failed to set field:\t" + field.InternalName + " : " + e.Message); } } outListItem.Update(); outFile.Update(); } catch (Exception e) { Console.WriteLine("Failed to set on:\t" + outFile.Url + " from : " + inFile.Url); Console.WriteLine(e.Message); } } web.AllowUnsafeUpdates = false; } }); Console.WriteLine("\t\t\tDeleting only items that successfully converted"); foreach (ConversionItemInfo convertedItem in convertedItems) { Console.WriteLine("Deleting item:\t\tName:" + convertedItem.InputFile); folderToConvert.Files.Delete(convertedItem.InputFile); } break; } Console.WriteLine("In progress:\t\tSuccessful: " + status.Succeeded + ", Failed: " + status.Failed); } Console.WriteLine("Done:\t\t\tFinished"); } }
public static bool ConvertLibrary(SPList list, string fileFormat, bool isWorkflow, ActivityExecutionContext executionContext) { ISharePointService wfService = null; if (executionContext != null) { wfService = executionContext.GetService <ISharePointService>(); } using (SPSite spSite = new SPSite(list.ParentWeb.Site.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { try { var proxies = SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy)); if (proxies.Any()) { _proxy = proxies.First(); } else { var exception = new SPException(); throw exception; } var job = new ConversionJob(_proxy.DisplayName) { UserToken = spSite.UserToken }; if (spSite.SiteSubscription != null) { job.SubscriptionId = spSite.SiteSubscription.Id; } job.Settings.OutputFormat = DeriveFileFormat(fileFormat); job.Name = list.Title + "-" + Guid.NewGuid(); job.AddLibrary(list, list); job.Start(); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted, 0, TimeSpan.Zero, "Information", "Conversion job queued for " + list.Title, string.Empty); } return(true); } catch (SPException exception) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to find the Word Automation Services Proxy", exception.StackTrace); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to find the" + "Word Automation Services Proxy for " + list.Title, exception.StackTrace); } return(false); } catch (InvalidOperationException exception2) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" + "Word Automation Service is Started.", exception2.StackTrace); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to contact the " + "Word Automation Services. Validate that the Word Automation Service is Started. Attempted to process file " + list.Title, exception2.StackTrace); } return(false); } } } }
public SPWordConversionJobPipeBind(ConversionJob job) : this(job.JobId) { }
public CancelConversionJobCommand(ConversionJob conversionJob) { this.conversionJob = conversionJob; }
static void Main(string[] args) { string siteURL = args[0]; string docLib = args[1]; using (SPSite spSite = new SPSite(siteURL)) { SPDocumentLibrary library = spSite.RootWeb.Lists[docLib] as SPDocumentLibrary; string docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Automation.xml"; SPFile file = spSite.RootWeb.GetFile(docPath); XDocument automation = XDocument.Load(new StreamReader(file.OpenBinaryStream())); XElement autoElement = automation.Element("Automation"); string masterName = autoElement.Attribute("Master").Value; string printerName = autoElement.Attribute("Printer").Value; // Open the master document docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/" + masterName + ".docx"; SPFile masterFile = spSite.RootWeb.GetFile(docPath); Stream docStream = new MemoryStream(); Stream docMasterStream = masterFile.OpenBinaryStream(); BinaryReader docMasterReader = new BinaryReader(docMasterStream); BinaryWriter docWriter = new BinaryWriter(docStream); docWriter.Write(docMasterReader.ReadBytes((int)docMasterStream.Length)); docWriter.Flush(); docMasterReader.Close(); docMasterStream.Dispose(); Package package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite); WordprocessingDocument master = WordprocessingDocument.Open(package); string guid; Uri XMLUri = CreateCustomXML(master, automation.Descendants("Record").First(), out guid); BindControls(master, guid); master.Close(); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output 00001.docx"; spSite.RootWeb.Files.Add(docPath, docStream, true); // Loop through all the records from the XML file int count = 1; foreach (XElement element in automation.Descendants("Record")) { if (count != 1) { package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite); master = WordprocessingDocument.Open(package); foreach (CustomXmlPart part in master.MainDocumentPart.CustomXmlParts) { if (part.Uri == XMLUri) { Stream stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(stream); sw.Write(element.ToString()); sw.Flush(); sw.Close(); break; } } master.Close(); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + count.ToString("D5") + ".docx"; spSite.RootWeb.Files.Add(docPath, docStream, true); } count++; } // Use Word Automation Services to convert to XPS files ConversionJob job = new ConversionJob(WordAutomationServicesName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.XPS; job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; SPList listToConvert = spSite.RootWeb.Lists[docLib]; job.AddLibrary(listToConvert, listToConvert); job.Start(); for (; ;) { Thread.Sleep(5000); ConversionJobStatus status = new ConversionJobStatus(WordAutomationServicesName, job.JobId, null); if (status.Count == status.Succeeded + status.Failed) { break; } } // Print output XPS files LocalPrintServer srv = new LocalPrintServer(); PrintQueue pq = srv.GetPrintQueue(printerName); for (int num = 1; num < count; num++) { XpsDocumentWriter xdw = PrintQueue.CreateXpsDocumentWriter(pq); docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + num.ToString("D5") + ".xps"; SPFile docFile = spSite.RootWeb.GetFile(docPath); package = Package.Open(docFile.OpenBinaryStream(), FileMode.Open, FileAccess.Read); XpsDocument xdoc = new XpsDocument(package); xdoc.Uri = new Uri(docPath); xdw.Write(xdoc.GetFixedDocumentSequence()); xdoc.Close(); } } }
private byte[] ConvertDocument(SPWeb web, byte[] docToConvert, string docFileName, bool isImmediate, String conversionLibName, int timeOutSecs, bool deleteDocs) { byte[] result = null; SPList conversionLib = web.Lists[conversionLibName]; SPFolder folder = conversionLib.RootFolder; // Get the default proxy for the current Word Automation Services instance SPServiceContext serviceContext = SPServiceContext.GetContext(web.Site); WordServiceApplicationProxy wordServiceApplicationProxy = (WordServiceApplicationProxy)serviceContext.GetDefaultProxy(typeof(WordServiceApplicationProxy)); ConversionJob job = new ConversionJob(wordServiceApplicationProxy); job.UserToken = web.CurrentUser.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; job.Settings.OutputFormat = SaveFormat.PDF; //String docFileName = Guid.NewGuid().ToString("D"); docFileName = Guid.NewGuid().ToString("D"); // we replace possible existing files on upload // although there is a minimal chance for GUID duplicates :-) SPFile docFile = folder.Files.Add(docFileName + ".docx", docToConvert, true); conversionLib.AddItem(docFileName + ".docx", SPFileSystemObjectType.File); String docFileUrl = String.Format("{0}/{1}", web.Url, docFile.Url); String pdfFileUrl = String.Format("{0}/{1}.pdf", web.Url, docFile.Url.Substring(0, docFile.Url.Length - 5)); job.AddFile(docFileUrl, pdfFileUrl); // let's do the job :-) // Start-SPTimerJob "Word Automation Services" job.Start(); if (isImmediate) { //Feature scope must be Web Application to use this function StartServiceJob("Word Automation Services Timer Job"); } ConversionJobStatus cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, job.JobId, null); // set up timeout TimeSpan timeSpan = new TimeSpan(0, 0, timeOutSecs); DateTime conversionStarted = DateTime.Now; int finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed; while ((finishedConversionCount != 1) && ((DateTime.Now - conversionStarted) < timeSpan)) { // wait a sec. Thread.Sleep(1000); cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, job.JobId, null); finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed; } // timeouted -> cancel conversion if (finishedConversionCount != 1) { job.Cancel(); } // we can output the possible failed conversion error(s) foreach (ConversionItemInfo cii in cjStatus.GetItems(ItemTypes.Failed)) { Utility.LogError(string.Format("Failed conversion. Input file: '{0}'; Output file: '{1}'; Error code: '{2}'; Error message: '{3}';", cii.InputFile, cii.OutputFile, cii.ErrorCode, cii.ErrorMessage), "Document Generator"); } SPFile convertedFile = web.GetFile(pdfFileUrl); // shouldn't be null (unless there is a conversion error) // but we check for sure if ((convertedFile != null) && (convertedFile.Exists)) { Stream pdfStream = convertedFile.OpenBinaryStream(); result = new byte[pdfStream.Length]; pdfStream.Read(result, 0, result.Length); // delete result doc if requested if (deleteDocs) { convertedFile.Delete(); } } // delete source doc if requested if (deleteDocs) { docFile.Delete(); } return result; }
protected void OnVideoConverterToolActionActivated (object sender, System.EventArgs e) { int res; VideoConversionTool converter = new VideoConversionTool (); res = converter.Run (); converter.Destroy (); if (res == (int)ResponseType.Ok) { ConversionJob job = new ConversionJob (converter.Files, converter.EncodingSettings); App.Current.JobsManager.Add (job); } }
public static bool ConvertFolder(SPFolder folderItem, string fileFormat, string location, bool isWorkflow, ActivityExecutionContext executionContext) { ISharePointService wfService = null; if (executionContext != null) { wfService = executionContext.GetService <ISharePointService>(); } if (string.IsNullOrEmpty(location)) { location = null; } using (SPSite spSite = new SPSite(location ?? SPContext.Current.Web.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { try { var proxies = SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy)); if (proxies.Any()) { _proxy = proxies.First(); } else { var exception = new SPException(); throw exception; } var job = new ConversionJob(_proxy.DisplayName) { UserToken = spSite.UserToken }; if (spSite.SiteSubscription != null) { job.SubscriptionId = spSite.SiteSubscription.Id; } job.Settings.OutputFormat = DeriveFileFormat(fileFormat); job.Name = folderItem.Name + "-" + Guid.NewGuid(); if (string.IsNullOrEmpty(location)) { job.AddFolder(folderItem, folderItem, true); } else { if (location.ToLower().Contains("http://")) { location = location.Remove(0, 7); } else if (location.ToLower().Contains("https://")) { location = location.Remove(0, 8); } var index = location.IndexOf('/'); if (index > 0) { location = location.Substring(index); } var list = spWeb.GetList(location); try { var folder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, folderItem.Name); folder["Title"] = folderItem.Name; folder.Update(); } catch (SPException) { //Folder already exists } var folder2 = list.RootFolder.SubFolders[folderItem.Name]; job.AddFolder(folderItem, folder2, true); } job.Start(); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted, 0, TimeSpan.Zero, "Information", "Conversion job queued for " + folderItem.Name, string.Empty); } return(true); } catch (SPException exception) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to find the Word Automation Services Proxy", exception.StackTrace); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to find the" + "Word Automation Services Proxy for " + folderItem.Name, exception.StackTrace); } return(false); } catch (InvalidOperationException exception2) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus", TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected, "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" + "Word Automation Service is Started.", exception2.StackTrace); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to contact the " + "Word Automation Services. Validate that the Word Automation Service is Started. Attempted to process file " + folderItem.Name, exception2.StackTrace); } return(false); } } } }
private void Initialize() { #if BUILD32 Diagnostics.Debug.Log("File Converter v" + ApplicationVersion.ToString() + " (32 bits)"); #else Diagnostics.Debug.Log("File Converter v" + ApplicationVersion.ToString() + " (64 bits)"); #endif // Retrieve arguments. Debug.Log("Retrieve arguments..."); string[] args = Environment.GetCommandLineArgs(); #if (DEBUG) { ////System.Array.Resize(ref args, 5); ////args[1] = "--conversion-preset"; ////args[2] = "To Png"; ////args[3] = "--verbose"; ////args[4] = @"D:\Test\images\Mario Big.png"; } #endif // Log arguments. for (int index = 0; index < args.Length; index++) { string argument = args[index]; Debug.Log("Arg{0}: {1}", index, argument); } Debug.Log(string.Empty); if (args.Length == 1) { // Diplay help windows to explain that this application is a context menu extension. ApplicationStartHelp applicationStartHelp = new ApplicationStartHelp(); applicationStartHelp.Show(); this.HideMainWindow = true; return; } // Parse arguments. List <string> filePaths = new List <string>(); string conversionPresetName = null; for (int index = 1; index < args.Length; index++) { string argument = args[index]; if (string.IsNullOrEmpty(argument)) { continue; } if (argument.StartsWith("--")) { // This is an optional parameter. string parameterTitle = argument.Substring(2).ToLowerInvariant(); switch (parameterTitle) { case "post-install-init": Settings.PostInstallationInitialization(); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; case "version": Console.Write(ApplicationVersion.ToString()); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; case "settings": this.ShowSettings = true; this.HideMainWindow = true; break; case "apply-settings": Settings.ApplyTemporarySettings(); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; case "conversion-preset": if (index >= args.Length - 1) { Debug.LogError("Invalid format. (code 0x01)"); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; } conversionPresetName = args[index + 1]; index++; continue; case "verbose": { this.Verbose = true; } break; default: Debug.LogError("Unknown application argument: '--{0}'.", parameterTitle); return; } } else { filePaths.Add(argument); } } // Load settigns. Debug.Log("Load settings..."); this.Settings = Settings.Load(); if (this.Settings == null) { Diagnostics.Debug.LogError("The application will now shutdown. If you want to fix the problem yourself please edit or delete the file: C:\\Users\\UserName\\AppData\\Local\\FileConverter\\Settings.user.xml."); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; } if (this.Settings.MaximumNumberOfSimultaneousConversions <= 0) { this.Settings.MaximumNumberOfSimultaneousConversions = System.Math.Max(1, Environment.ProcessorCount / 2); Diagnostics.Debug.Log("The number of processors on this computer is {0}. Set the default number of conversion threads to {0}", this.Settings.MaximumNumberOfSimultaneousConversions); } this.numberOfConversionThread = this.Settings.MaximumNumberOfSimultaneousConversions; Diagnostics.Debug.Log("Maximum number of conversion threads: {0}", this.numberOfConversionThread); // Check upgrade. if (this.Settings.CheckUpgradeAtStartup) { #if DEBUG Task <UpgradeVersionDescription> task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription); #else long fileTime = Registry.GetValue <long>(Registry.Keys.LastUpdateCheckDate); DateTime lastUpdateDateTime = DateTime.FromFileTime(fileTime); TimeSpan durationSinceLastUpdate = DateTime.Now.Subtract(lastUpdateDateTime); if (durationSinceLastUpdate > new TimeSpan(1, 0, 0, 0)) { Task <UpgradeVersionDescription> task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription); } #endif } ConversionPreset conversionPreset = null; if (!string.IsNullOrEmpty(conversionPresetName)) { conversionPreset = this.Settings.GetPresetFromName(conversionPresetName); if (conversionPreset == null) { Debug.LogError("Invalid conversion preset '{0}'. (code 0x02)", conversionPresetName); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; } } if (conversionPreset != null) { // Create convertion jobs. Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.Name); try { for (int index = 0; index < filePaths.Count; index++) { string inputFilePath = filePaths[index]; ConversionJob conversionJob = ConversionJobFactory.Create(conversionPreset, inputFilePath); this.conversionJobs.Add(conversionJob); } } catch (Exception exception) { Debug.LogError(exception.Message); throw; } this.needToRunConversionThread = true; } }
/// <summary> /// Adds a conversion job to the queue /// This function does NOT take a lock on the queue before modifying it. This function is not thread safe /// </summary> /// <param name="filePath">File to add</param> /// <param name="monitorTask">Monitor task name which found the file</param> /// <param name="manual">True if this is a manuall added entry, false if it's added by a monitor task</param> private void AddJobs(string filePath, MonitorJobOptions monitorTask, bool manual) { bool filterMatchSuccessful = false; // Check if the file has already been processed in the past if so skip if (_conversionTaskFilterMismatchFiles.Contains(filePath)) { return; // } foreach (ConversionJobOptions conversionTask in MCEBuddyConf.GlobalMCEConfig.AllConversionTasks) { // Check if the task is disabled, which case skip if (!conversionTask.enabled) { Log.AppLog.WriteEntry(this, Localise.GetPhrase("Conversion Task") + " " + conversionTask.taskName + " " + Localise.GetPhrase("disabled, skipping file") + " " + filePath, Log.LogEntryType.Debug, true); continue; } conversionTask.sourceVideo = filePath; // Monitor Task name matching if not empty if ((monitorTask != null) && !String.IsNullOrWhiteSpace(monitorTask.taskName) && (conversionTask.monitorTaskNames != null)) { bool foundMatch = false; foreach (string matchMonitorTaskName in conversionTask.monitorTaskNames) { if (monitorTask.taskName.ToLower().Trim() != matchMonitorTaskName.ToLower().Trim()) // match the list of a name { continue; // move onto next monitor task name } else { foundMatch = true; break; } } if (!foundMatch) { Log.AppLog.WriteEntry(this, "Skipping Conversion task " + conversionTask.taskName + " for file " + filePath + " since Monitor task " + monitorTask.taskName + " does not match the list of monitor tasks in the conversion task.", Log.LogEntryType.Debug, true); continue; // move into next conversion task } } // Metadata extract and pattern match from conversion task VideoMetaData metaData = MetadataMatchFilters(conversionTask); if (metaData != null) // We got a match - process the file { // Calculate where to add the job in the queue int idx; if (manual || conversionTask.insertQueueTop) // Manual jobs to the head of the queue, just after the current active job, or check if the conversion task is asking to add the job at the head of the queue { for (idx = 0; idx < _jobQueue.Count; idx++) { if (!_jobQueue[idx].Active) { break; } } } else { idx = _jobQueue.Count; // Add the job to the end of the active queue } // If it's a manual entry then we need to convert, reset the skip reconverting flag if it's set if (manual && conversionTask.skipReprocessing) { conversionTask.skipReprocessing = conversionTask.checkReprocessingHistory = false; // We can make a direct change since this is a copy object Log.AppLog.WriteEntry(this, "Manually added file, resetting the skip reprocessing option, the file will converted even if it has been processed before", Log.LogEntryType.Debug, true); } Log.AppLog.WriteEntry(this, Localise.GetPhrase("Added new job to queue for") + " " + filePath, Log.LogEntryType.Information, true); ConversionJob job = new ConversionJob(conversionTask, monitorTask, metaData); _jobQueue.Insert(idx, job); filterMatchSuccessful = true; // we cleared filters and processed the file // Send an eMail if required GeneralOptions go = MCEBuddyConf.GlobalMCEConfig.GeneralOptions; bool sendEMail = go.sendEmail; // do we need to send an eMail after adding a job to the queue bool sendQueue = go.eMailSettings.queueEvent; string sendQueueSubject = go.eMailSettings.queueSubject; bool skipBody = go.eMailSettings.skipBody; if (sendEMail && sendQueue) { string subject = Localise.GetPhrase("MCEBuddy added a video conversion to the queue"); string message = Localise.GetPhrase("Source Video") + " -> " + job.OriginalFileName + "\r\n"; message += Localise.GetPhrase("Profile") + " -> " + job.Profile + "\r\n"; message += Localise.GetPhrase("Conversion Task") + " -> " + job.TaskName + "\r\n"; // Check for custom subject and process if (!String.IsNullOrWhiteSpace(sendQueueSubject)) { subject = UserCustomParams.CustomParamsReplace(sendQueueSubject, job.WorkingPath, "", "", job.OriginalFileName, "", "", "", job.Profile, job.TaskName, conversionTask.relativeSourcePath, metaData.MetaData, Log.AppLog); } eMailSendEngine.AddEmailToSendQueue(subject, (skipBody ? "" : message)); // Send the eMail through the eMail engine } } else if (manual) // Delete manual file entry if we didn't create a conversion job, otherwise the engine will clear it on completion { // Manual files may be added multiple times and the filter may already have it from the last time, so be safe and delete it Ini iniManualQueue = new Ini(GlobalDefs.ManualQueueFile); // Delete the entry from the manual queue iniManualQueue.DeleteKey("ManualQueue", filePath); } } // If we have been through all the conversion tasks and not a single task has processed this file, hence we add it to the filter mismatch list so it won't be processed in future (MetadataExtract is very intensive and also prevent overburdening the log file) if (!filterMatchSuccessful) { _conversionTaskFilterMismatchFiles.Add(filePath); } }
public static bool ConvertDocument(SPListItem listItem, string fileFormat, string newFileName, bool isWorkflow, ActivityExecutionContext executionContext, WorkflowContext __Context, SPFolder folder, string settings, bool isImmediate) { ISharePointService wfService = null; if (executionContext != null) { wfService = executionContext.GetService <ISharePointService>(); } using (SPSite spSite = new SPSite(listItem.ParentList.ParentWeb.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { int i = listItem.Url.IndexOf("/"); var listUrl = listItem.Url.Remove(i + 1); var listItemUri = new Uri(listItem.Web.Url + "/" + listItem.Url); var listItemLibraryUri = new Uri(listItem.Web.Url + "/" + listUrl); var fileName = listItem.Name; var idx = fileName.LastIndexOf(".", StringComparison.Ordinal); if (string.IsNullOrEmpty(newFileName)) { newFileName = fileName.Replace(fileName.Substring(idx, fileName.Length - idx), "." + fileFormat); } else { if (isWorkflow) { newFileName = newFileName + fileName.Replace(fileName.Substring(idx, fileName.Length - idx), "." + fileFormat); } } try { var proxies = SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy)); if (proxies.Any()) { _proxy = proxies.First(); } else { var exception = new SPException(); throw exception; } #region ImmediateJob if (isImmediate) { SyncConverter immJob; if (isWorkflow) { immJob = new SyncConverter(_proxy.DisplayName) { UserToken = __Context.InitiatorUser.UserToken }; } else { immJob = new SyncConverter(_proxy.DisplayName) { UserToken = spSite.UserToken }; } if (spSite.SiteSubscription != null) { immJob.SubscriptionId = spSite.SiteSubscription.Id; } immJob.Settings.OutputFormat = DeriveFileFormat(fileFormat); if (!string.IsNullOrEmpty(settings)) { var splitSettings = settings.Split(';'); if (fileFormat.ToLower(CultureInfo.InvariantCulture) == splitSettings[0].Remove(0, 2).ToLower(CultureInfo.InvariantCulture)) { switch (fileFormat) { case "xps": case "pdf": { immJob.Settings.FixedFormatSettings.Bookmarks = (FixedFormatBookmark) Enum.Parse(typeof(FixedFormatBookmark), splitSettings[1].Remove(0, 2)); immJob.Settings.FixedFormatSettings.BalloonState = (BalloonState) Enum.Parse(typeof(BalloonState), splitSettings[2].Remove(0, 2)); if (splitSettings.Contains("BitmapEmbeddedFonts")) { immJob.Settings.FixedFormatSettings.BitmapEmbeddedFonts = true; } if (splitSettings.Contains("IncludeDocumentProperties")) { immJob.Settings.FixedFormatSettings.IncludeDocumentProperties = true; } if (splitSettings.Contains("IncludeDocumentStructure")) { immJob.Settings.FixedFormatSettings.IncludeDocumentStructure = true; } if (splitSettings.Contains("OptimizeForMinimumSize")) { immJob.Settings.FixedFormatSettings.OutputQuality = FixedFormatQuality.Minimum; } if (splitSettings.Contains("UsePdfA")) { immJob.Settings.FixedFormatSettings.UsePDFA = true; } break; } case "doc": case "docx": case "docm": case "dot": case "dotx": case "dotm": { immJob.Settings.CompatibilityMode = (CompatibilityMode) Enum.Parse(typeof(CompatibilityMode), splitSettings[1].Remove(0, 2)); if (splitSettings.Contains("AddThumbnail")) { immJob.Settings.AddThumbnail = true; } if (splitSettings.Contains("EmbedFonts")) { immJob.Settings.AddThumbnail = true; } if (splitSettings.Contains("UpdateFields")) { immJob.Settings.UpdateFields = true; } break; } } } } var sStream = new SPFileStream(spWeb, 0x1000); var inputStream = listItem.File.OpenBinaryStream(); immJob.Convert(inputStream, sStream); try { if (folder == null) { listItem.Folder.Files.Add(newFileName, sStream); } else { if (spWeb.Url != folder.ParentWeb.Url) { using (SPWeb web2 = spSite.OpenWeb(folder.ParentWeb.Url)) { folder.Files.Add(newFileName, sStream); } } folder.Files.Add(newFileName, sStream); } } catch (Exception exception) { if (wfService != null) { Exceptions.CheckedOutException(exception, listItem, wfService, executionContext); return(false); } Exceptions.CheckedOutException(exception, listItem, null, null); return(false); } return(true); } #endregion #region Timer Conversion Job else { ConversionJob job; if (isWorkflow) { job = new ConversionJob(_proxy.DisplayName) { UserToken = __Context.InitiatorUser.UserToken }; } else { job = new ConversionJob(_proxy.DisplayName) { UserToken = spSite.UserToken }; } if (spSite.SiteSubscription != null) { job.SubscriptionId = spSite.SiteSubscription.Id; } job.Settings.OutputFormat = DeriveFileFormat(fileFormat); job.Name = listItem.Name + "-" + Guid.NewGuid(); if (!string.IsNullOrEmpty(settings)) { var splitSettings = settings.Split(';'); if (fileFormat.ToLower(CultureInfo.InvariantCulture) == splitSettings[0].Remove(0, 2).ToLower(CultureInfo.InvariantCulture)) { switch (fileFormat) { case "xps": case "pdf": { job.Settings.FixedFormatSettings.Bookmarks = (FixedFormatBookmark) Enum.Parse(typeof(FixedFormatBookmark), splitSettings[1].Remove(0, 2)); job.Settings.FixedFormatSettings.BalloonState = (BalloonState) Enum.Parse(typeof(BalloonState), splitSettings[2].Remove(0, 2)); if (splitSettings.Contains("BitmapEmbeddedFonts")) { job.Settings.FixedFormatSettings.BitmapEmbeddedFonts = true; } if (splitSettings.Contains("IncludeDocumentProperties")) { job.Settings.FixedFormatSettings.IncludeDocumentProperties = true; } if (splitSettings.Contains("IncludeDocumentStructure")) { job.Settings.FixedFormatSettings.IncludeDocumentStructure = true; } if (splitSettings.Contains("OptimizeForMinimumSize")) { job.Settings.FixedFormatSettings.OutputQuality = FixedFormatQuality.Minimum; } if (splitSettings.Contains("UsePdfA")) { job.Settings.FixedFormatSettings.UsePDFA = true; } break; } case "doc": case "docx": case "docm": case "dot": case "dotx": case "dotm": { job.Settings.CompatibilityMode = (CompatibilityMode) Enum.Parse(typeof(CompatibilityMode), splitSettings[1].Remove(0, 2)); if (splitSettings.Contains("AddThumbnail")) { job.Settings.AddThumbnail = true; } if (splitSettings.Contains("EmbedFonts")) { job.Settings.EmbedFonts = true; } if (splitSettings.Contains("UpdateFields")) { job.Settings.UpdateFields = true; } break; } } } } try { if (folder == null) { job.AddFile(listItemUri.ToString(), listItemLibraryUri + newFileName); } else { job.AddFile(listItemUri.ToString(), string.Format("{0}/{1}/{2}", folder.ParentWeb.Url, folder.Url, newFileName)); } } catch (Exception exception) { if (wfService != null) { Exceptions.CheckedOutException(exception, listItem, wfService, executionContext); return(false); } Exceptions.CheckedOutException(exception, listItem, null, null); return(false); } job.Start(); if (wfService != null) { wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted, 0, TimeSpan.Zero, "Information", "Conversion job queued for " + listItem.DisplayName, string.Empty); } return(true); #endregion } } catch (SPException exception) { if (wfService != null) { Exceptions.SharePointException(exception, listItem, wfService, executionContext); return(false); } Exceptions.SharePointException(exception, listItem, null, null); return(false); } catch (InvalidOperationException exception) { if (wfService != null) { Exceptions.InvalidOperationException(exception, listItem, wfService, executionContext); return(false); } Exceptions.InvalidOperationException(exception, listItem, null, null); return(false); } } } }