/// <summary> /// This node will open the given file in the background. /// </summary> /// <param name="filePath">The file to obtain document from.</param> /// <param name="audit">Choose whether or not to audit the file upon opening. (Will run slower with this)</param> /// <param name="detachFromCentral">Choose whether or not to detach from central upon opening. Only for RVT files. </param> /// <param name="preserveWorksets">Choose whether or not to preserve worksets upon opening. Only for RVT files. </param> /// <returns name="document">The document object. If the file path is blank this returns the current document.</returns> /// <search> /// Application.OpenDocumentFile, rhythm /// </search> public static object OpenDocumentFile(string filePath, bool audit = false, bool detachFromCentral = false, bool preserveWorksets = true) { var uiapp = DocumentManager.Instance.CurrentUIApplication; var app = uiapp.Application; //instantiate open options for user to pick to audit or not OpenOptions openOpts = new OpenOptions(); openOpts.Audit = audit; //TransmittedModelOptions tOpt = TransmittedModelOptions.SaveAsNewCentral; openOpts.DetachFromCentralOption = detachFromCentral == false ? DetachFromCentralOption.DoNotDetach : preserveWorksets == true ? DetachFromCentralOption.DetachAndPreserveWorksets : DetachFromCentralOption.DetachAndDiscardWorksets; //convert string to model path for open ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); var document = app.OpenDocumentFile(modelPath, openOpts); return(document); }
public DocumentFormatReader(Uri address, OpenOptions options = null) { _request = (HttpWebRequest)WebRequest.Create(address); if (options != null) { if (options.SkipContent) { _request.Method = WebRequestMethods.Http.Head; } if (options.RangeFrom.HasValue) { if (options.RangeTo.HasValue) _request.AddRange(options.RangeFrom.Value, options.RangeTo.Value); else _request.AddRange(options.RangeFrom.Value); } } }
/// <summary> /// Closes the document safely. /// </summary> /// <param name="doc"></param> /// <param name="uiapp"></param> /// <param name="tmpRvt"></param> /// <param name="saveModified"></param> public static void SafelyClose(this Document doc, UIApplication uiapp, string tmpRvt, bool saveModified = true) { if (doc is null) { throw new ArgumentNullException(nameof(doc)); } if (uiapp is null) { throw new ArgumentNullException(nameof(uiapp)); } if (tmpRvt is null) { throw new ArgumentNullException(nameof(tmpRvt)); } if (Equals(uiapp.ActiveUIDocument.Document, doc)) { var modelPath = new FilePath(tmpRvt); var opt = new OpenOptions(); uiapp.OpenAndActivateDocument(modelPath, opt, false); } // Before closing active document, must open another a document and active it. if (saveModified) { if (string.IsNullOrWhiteSpace(doc.PathName)) { throw new Exception("The document file doesn't exist, please save it!"); } doc.Close(true); } else { doc.Close(false); } }
/// <summary> /// detachs from the central file. /// </summary> /// <param name="app"></param> /// <param name="centralPath"></param> /// <returns></returns> public static Document DetachedFromCentralFile(this Application app, string centralPath) { if (app is null) { throw new ArgumentNullException(nameof(app)); } if (centralPath is null) { throw new ArgumentNullException(nameof(centralPath)); } var modelPath = new FilePath(centralPath); var option = new OpenOptions { AllowOpeningLocalByWrongUser = true, DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets }; return(app.OpenDocumentFile(modelPath, option)); }
private Document CreateLocal(UIApplication uiapp, string path) { string modelname = Path.GetFileNameWithoutExtension(path); ModelPath modelpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path); Directory.CreateDirectory(TempPath); ModelPath targetpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(TempPath + modelname); WorksharingUtils.CreateNewLocal(modelpath, targetpath); OpenOptions openoptions = new OpenOptions { DetachFromCentralOption = DetachFromCentralOption.DoNotDetach }; Document doc = uiapp.Application.OpenDocumentFile(targetpath, openoptions); return(doc); }
public static Dictionary <string, object> openDocumentOption(bool audit = false, int detachFromCentralOption = 3) { string message = ""; OpenOptions openOpt = new OpenOptions(); //Document doc = DocumentManager.Instance.CurrentDBDocument; //Document openedDoc = null; //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication; //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument; //ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath); try { openOpt.Audit = false; WorksetConfiguration workConf = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets); openOpt.SetOpenWorksetsConfiguration(workConf); switch (detachFromCentralOption) { case 0: openOpt.DetachFromCentralOption = DetachFromCentralOption.ClearTransmittedSaveAsNewCentral; break; case 1: openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; break; case 2: openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; break; case 3: openOpt.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach; break; } } catch (Exception ex) { message = ex.Message; } return(new Dictionary <string, object> { { "openOption", openOpt }, }); }
public void SaveDetachDisworksets() { string mpath = ""; string mpathOnlyFilename = ""; FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local"; folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { mpath = folderBrowserDialog1.SelectedPath; FileInfo filePath = new FileInfo(projectPath); ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName); OpenOptions opt = new OpenOptions(); opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; mpathOnlyFilename = filePath.Name; Document openedDoc = app.OpenDocumentFile(mp, opt); SaveAsOptions options = new SaveAsOptions(); options.OverwriteExistingFile = true; ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + "Detached" + "_" + datetimesave + "_" + mpathOnlyFilename); openedDoc.SaveAs(modelPathout, options); openedDoc.Close(true); } }
public void SaveDetach(Document doc) { System.Windows.Forms.OpenFileDialog theDialogRevit = new System.Windows.Forms.OpenFileDialog(); theDialogRevit.Title = "Select Revit Project Files"; theDialogRevit.Filter = "RVT files|*.rvt"; theDialogRevit.FilterIndex = 1; theDialogRevit.InitialDirectory = @"C:\"; theDialogRevit.Multiselect = true; if (theDialogRevit.ShowDialog() == DialogResult.OK) { string mpath = ""; string mpathOnlyFilename = ""; System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local"; folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { mpath = folderBrowserDialog1.SelectedPath; foreach (string projectPath in theDialogRevit.FileNames) { FileInfo filePath = new FileInfo(projectPath); ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName); OpenOptions opt = new OpenOptions(); opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; mpathOnlyFilename = filePath.Name; Document openedDoc = app.OpenDocumentFile(mp, opt); SaveAsOptions options = new SaveAsOptions(); options.OverwriteExistingFile = true; ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + mpathOnlyFilename); openedDoc.SaveAs(modelPathout, options); openedDoc.Close(false); } } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Application app = uiapp.Application; int check = 0; int sheetsNumber = 0; int viewsNumber = 0; int schedulesNumber = 0; int furnitureElements = 0; using (var formOpen = new FormOpenFile()) { formOpen.ShowDialog(); string fileName = formOpen.filePath; ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(fileName); if (formOpen.DialogResult == winForms.DialogResult.OK) { OpenOptions optionDetach = new OpenOptions(); optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; optionDetach.Audit = true; openDoc = app.OpenDocumentFile(modelP, optionDetach); IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(openDoc).OfClass(typeof(ViewFamilyType)) let type = elem as ViewFamilyType where type.ViewFamily == ViewFamily.ThreeDimensional select type; IEnumerable <ElementId> sheetIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Sheets) select elem.Id; IEnumerable <ElementId> viewsIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views) where elem.Name != "Clarity_IFC _3D" select elem.Id; #if REVIT2019 IEnumerable <ElementId> schedulesIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Schedules) select elem.Id; #elif REVIT2017 #endif List <BuiltInCategory> builtInCats = new List <BuiltInCategory>(); builtInCats.Add(BuiltInCategory.OST_Furniture); builtInCats.Add(BuiltInCategory.OST_Casework); builtInCats.Add(BuiltInCategory.OST_Planting); builtInCats.Add(BuiltInCategory.OST_Entourage); builtInCats.Add(BuiltInCategory.OST_Railings); builtInCats.Add(BuiltInCategory.OST_StairsRailing); ElementMulticategoryFilter filter1 = new ElementMulticategoryFilter(builtInCats); View3D view3d = null; using (Transaction tran = new Transaction(openDoc)) { tran.Start("Clarity Setup"); FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(openDoc).OfKind(WorksetKind.UserWorkset); try { view3d = View3D.CreateIsometric(openDoc, viewFamilyTypes.First().Id); view3d.Name = "Clarity_IFC _3D"; //uiapp.ActiveUIDocument.ActiveView = view3d; foreach (Workset e in worksetCollector) { view3d.SetWorksetVisibility(e.Id, WorksetVisibility.Visible); } } catch (Exception ex) { TaskDialog.Show("Error", "Name already taken" + "\n" + ex.Message); } try { sheetsNumber += sheetIds.Count(); if (sheetIds.Count() > 0) { openDoc.Delete(sheetIds.ToList()); } } catch (Exception ex) { TaskDialog.Show("Sheets Error", ex.Message); } try { viewsNumber += viewsIds.Count(); if (viewsIds.Count() > 0) { openDoc.Delete(viewsIds.ToList()); } } catch (Exception ex) { TaskDialog.Show("Views Error", ex.Message); } #if REVIT2019 try { if (schedulesIds.Count() > 0) { openDoc.Delete(schedulesIds.ToList()); schedulesNumber += schedulesIds.Count(); } } catch (Exception ex) { TaskDialog.Show("Schedule Error", ex.Message); } #elif REVIT2017 #endif if (formOpen.cleanArchModel) { int furnitureError = 0; ICollection <ElementId> toDelete = new FilteredElementCollector(openDoc).WherePasses(filter1).ToElementIds(); if (toDelete.Count() > 0) { string lastEx = ""; foreach (ElementId id in toDelete) { try { openDoc.Delete(id); furnitureElements += 1; } catch (Exception ex) { lastEx = $"{ex.Message}\n"; } } //Debug.WriteLine(lastEx.Message); TaskDialog.Show("Error", $"{furnitureElements} elements deleted. {furnitureError} cannot be deleted. Errors:\n{lastEx}"); } } if (formOpen.purgeModel) { ICollection <ElementId> purgeableElements = null; PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements); try { while (purgeableElements.Count > 0) { //TaskDialog.Show("Purge Count", purgeableElements.Count().ToString()); PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements); openDoc.Delete(purgeableElements); } } catch (Exception ex) { TaskDialog.Show("Purge Error", ex.Message); } } tran.Commit(); } SaveAsOptions saveOpt = new SaveAsOptions(); WorksharingSaveAsOptions wos = new WorksharingSaveAsOptions(); wos.SaveAsCentral = true; saveOpt.Compact = true; saveOpt.SetWorksharingOptions(wos); saveOpt.OverwriteExistingFile = true; openDoc.SaveAs(modelP, saveOpt); check += 1; } else { TaskDialog.Show("Result", "Command aborted."); } if (check > 0) { ICollection <ElementId> viewsId = new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views).ToElementIds(); string viewsNames = ""; foreach (ElementId eid in viewsId) { viewsNames += openDoc.GetElement(eid).Name + Environment.NewLine; } TaskDialog.Show("Result", String.Format("Sheets deleted {0} \nViews deleted {1} \nSchedules deleted {2} \nViews in the model {3}", sheetsNumber, viewsNumber, furnitureElements, viewsNames)); } //PurgeMaterials(openDoc); too slooooooow }//close using return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; DestinationPath = string.Empty; Documents = new List <string>(); Splash = string.Empty; Errors = new List <string[]>(); string date = DateTime.Now.ToString("dd/MM/yyyy"); int completed = 0; int failed = 0; ExportDialog exportdialog = new ExportDialog(); System.Windows.Forms.DialogResult dialog = exportdialog.ShowDialog(); if (dialog != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } WorksetConfiguration openconfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); OpenOptions openoptions = new OpenOptions(); openoptions.SetOpenWorksetsConfiguration(openconfig); if (exportdialog.DiscardRadioButton.Checked) { openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; } else { openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; } SaveAsOptions worksharedsaveas = new SaveAsOptions(); WorksharingSaveAsOptions saveConfig = new WorksharingSaveAsOptions { SaveAsCentral = true }; worksharedsaveas.SetWorksharingOptions(saveConfig); worksharedsaveas.OverwriteExistingFile = true; SaveAsOptions regularsaveas = new SaveAsOptions { OverwriteExistingFile = true }; if (exportdialog.AuditCheckBox.Checked) { openoptions.Audit = true; } if (exportdialog.SafeNameTextbox.Text.Trim() != string.Empty) { Splash = exportdialog.SafeNameTextbox.Text.Trim(); } string customdate = exportdialog.DateTimePickerIssue.Value.ToString("yyyy/MM/dd"); string nameprefix = exportdialog.PrefixTextBox.Text.Trim(); string namesuffix = exportdialog.SuffixTextBox.Text.Trim(); bool samepath = false; List <string[]> results = new List <string[]>(); foreach (string path in Documents) { string destdoc = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix + ".rvt"; if (File.Exists(DestinationPath + destdoc)) { samepath = true; break; } string pathonly = Path.GetDirectoryName(path) + "\\"; if (pathonly == DestinationPath) { samepath = true; break; } } if (samepath) { TaskDialog td = new TaskDialog("Export") { MainInstruction = "Some documents already exist in the destination path.", MainContent = "The files will be overritten, do you wish to continue?" }; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel"); switch (td.Show()) { case TaskDialogResult.CommandLink1: break; case TaskDialogResult.CommandLink2: return(Result.Cancelled); default: return(Result.Cancelled); } } uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); uiapp.Application.FailuresProcessing += FailureProcessor; DateTime start = DateTime.Now; foreach (string path in Documents) { string[] result = new string[6]; string resultmessage = string.Empty; if (!File.Exists(path)) { result[0] = Path.GetFileName(path); result[1] = "File Not Found"; result[2] = string.Empty; results.Add(result); failed++; continue; } DateTime s1 = DateTime.Now; Document doc = null; //try //{ doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openoptions); string docname = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix; using (Transaction t = new Transaction(doc, "Export")) { t.Start(); if (exportdialog.AutoCheckBox.Checked) { doc.ProjectInformation.IssueDate = date; } else { doc.ProjectInformation.IssueDate = customdate; } if (exportdialog.RemoveCADLinksCheckBox.Checked) { DeleteCADLinks(doc); } if (exportdialog.RemoveCADImportsCheckBox.Checked) { DeleteCADImports(doc); } if (exportdialog.RemoveRVTLinksCheckBox.Checked) { DeleteRVTLinks(doc); } DeleteViewsAndSheets(doc, exportdialog.ViewsONSheetsCheckBox.Checked, exportdialog.ViewsNOTSheetsCheckBox.Checked, exportdialog.SheetsCheckBox.Checked, exportdialog.TemplatesCheckBox.Checked); if (exportdialog.RemoveSchedulesCheckBox.Checked) { DeleteSchedules(doc); } if (exportdialog.UngroupCheckBox.Checked) { UngroupGroups(doc); } if (exportdialog.PurgeCheckBox.Checked) { PurgeDocument(doc); } t.Commit(); } if (doc.IsWorkshared) { doc.SaveAs(DestinationPath + docname + ".rvt", worksharedsaveas); } else { doc.SaveAs(DestinationPath + docname + ".rvt", regularsaveas); } doc.Close(false); string backupfolder = DestinationPath + docname + "_backup"; string tempfolder = DestinationPath + "Revit_temp"; if (Directory.Exists(backupfolder)) { Directory.Delete(backupfolder, true); } if (Directory.Exists(tempfolder)) { Directory.Delete(tempfolder, true); } resultmessage = "Completed"; completed++; //} // catch (Exception e) //{ // try // { // doc.Close(false); // } // catch { } // resultmessage = e.Message; // failed++; //} DateTime e1 = DateTime.Now; int h = (e1 - s1).Hours; int m = (e1 - s1).Minutes; int s = (e1 - s1).Seconds; result[0] = Path.GetFileName(path); result[1] = resultmessage; result[2] = h.ToString() + ":" + m.ToString() + ":" + s.ToString(); results.Add(result); } uiapp.DialogBoxShowing -= OnDialogBoxShowing; uiapp.Application.FailuresProcessing -= FailureProcessor; DateTime end = DateTime.Now; int hours = (end - start).Hours; int minutes = (end - start).Minutes; int seconds = (end - start).Seconds; TaskDialog rd = new TaskDialog("Export") { MainInstruction = "Results", MainContent = "Exported to: " + DestinationPath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s" }; rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close"); rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details"); switch (rd.Show()) { case TaskDialogResult.CommandLink1: return(Result.Succeeded); case TaskDialogResult.CommandLink2: ResultsDialog resultsdialog = new ResultsDialog(); foreach (string[] r in results) { var item = new System.Windows.Forms.ListViewItem(r); resultsdialog.ResultsView.Items.Add(item); } var rdialog = resultsdialog.ShowDialog(); return(Result.Succeeded); default: return(Result.Succeeded); } }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Delete any processed files from a previous run foreach (FileInfo f in new DirectoryInfo(".").GetFiles("*_ocr.pdf")) { f.Delete(); } // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { // ** If nothing is specified then read the first PDF file from the current folder. string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to OCR."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = Path.GetExtension(sourceFileName); // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = new ConversionSettings(); // ** OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCRSettings ocr = new OCRSettings(); ocr.Language = OCRLanguage.English.ToString(); ocr.Performance = OCRPerformance.Slow; ocr.WhiteList = string.Empty; ocr.BlackList = string.Empty; conversionSettings.OCRSettings = ocr; // ** OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR // ** Carry out the conversion. Console.WriteLine("Processing file " + sourceFileName + "."); byte[] convFile = client.ProcessChanges(sourceFile, openOptions, conversionSettings); // ** Write the processed file back to the file system with a PDF extension. string destinationFileName = Path.GetFileNameWithoutExtension(sourceFileName) + "_ocr.pdf"; using (FileStream fs = File.Create(destinationFileName)) { fs.Write(convFile, 0, convFile.Length); fs.Close(); } Console.WriteLine("File written to " + destinationFileName); // ** Open the generated PDF file in a PDF Reader Console.WriteLine("Launching file in PDF Reader"); Process.Start(destinationFileName); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } Console.ReadKey(); }
public Result Execute(UIApplication app) { if (ModuleData.up_send_enter) { Thread thread = new Thread(() => { var autoEvent = new AutoResetEvent(true); _Timer = new System.Threading.Timer(UiInput.KeyEnter, autoEvent, 20000, 20000); }); thread.Start(); } try { string assemblyPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; Print(string.Format("[{0}] Запуск...", DateTime.Now.ToString("T")), KPLN_Loader.Preferences.MessageType.Header); ModuleData.AutoConfirmEnabled = true; if (app.Application.Documents.IsEmpty) { Print("Создание [placeholder] документа...", KPLN_Loader.Preferences.MessageType.Regular); app.Application.NewProjectDocument(UnitSystem.Metric); } int max = Documents.Count; int step = 0; foreach (DbDocument doc in Documents) { step++; string step_info = string.Format("[{0}/{1}]", step.ToString(), max.ToString()); try { Print(string.Format("[{0}] Открытие {1}...", DateTime.Now.ToString("T"), doc.Path), KPLN_Loader.Preferences.MessageType.Header); ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(doc.Path); OpenOptions options = new OpenOptions() { DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets, Audit = false }; WorksetConfiguration config = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets); options.SetOpenWorksetsConfiguration(config); Document docu = app.Application.OpenDocumentFile(path, options); try { DbRowData rowData = new DbRowData(); rowData.Errors.Add(new DbError("Ошибка привязки к уровню", CheckTools.CheckLevels(docu))); rowData.Errors.Add(new DbError("Зеркальные элементы", CheckTools.CheckMirrored(docu))); rowData.Errors.Add(new DbError("Ошибка мониторинга осей", CheckTools.CheckMonitorGrids(docu))); rowData.Errors.Add(new DbError("Ошибка мониторинга уровней", CheckTools.CheckMonitorLevels(docu))); rowData.Errors.Add(new DbError("Дубликаты имен", CheckTools.CheckNames(docu))); rowData.Errors.Add(new DbError("Ошибки подгруженных связей", CheckTools.CheckSharedLocations(docu) + CheckTools.CheckLinkWorkSets(docu))); rowData.Errors.Add(new DbError("Предупреждения Revit", CheckTools.CheckErrors(docu))); rowData.Errors.Add(new DbError("Размер файла", CheckTools.CheckFileSize(doc.Path))); rowData.Errors.Add(new DbError("Элементы в наборах подгруженных связей", CheckTools.CheckElementsWorksets(docu))); DbController.WriteValue(doc.Id.ToString(), rowData.ToString()); Print(string.Format("[{0}] Закрытие документа...", DateTime.Now.ToString("T")), KPLN_Loader.Preferences.MessageType.Header); } catch (Exception e) { PrintError(e); } docu.Close(false); } catch (Exception e) { PrintError(e); } } ModuleData.AutoConfirmEnabled = false; _Timer.Dispose(); return(Result.Succeeded); } catch (Exception e) { ModuleData.AutoConfirmEnabled = false; PrintError(e); _Timer.Dispose(); return(Result.Failed); } }
public void open(OpenOptions options, ICallback success, ICallback error) { QueueWithCancellation(async() => { var dbFileName = options.Name; if (dbFileName == null) { error.Invoke("You must specify database name"); return; } if (_openDBs.ContainsKey(dbFileName)) { success.Invoke("Database opened"); return; } var assetFileOp = ResolveAssetFile(options.AssetFileName, dbFileName); var assetFile = assetFileOp == null ? null : await assetFileOp; // NoMutex means SQLite can be safely used by multiple threads provided that no // single database connection is used simultaneously in two or more threads. SQLite.Net.Interop.SQLiteOpenFlags sqlOpenFlags = SQLite.Net.Interop.SQLiteOpenFlags.NoMutex; string absoluteDbPath; if (options.ReadOnly && assetFileOp != null) { sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadOnly; absoluteDbPath = assetFile.Path; } else { sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadWrite | SQLite.Net.Interop.SQLiteOpenFlags.Create; absoluteDbPath = ResolveDbFilePath(dbFileName); // Option to create from resource (pre-populated) if db does not exist: if (assetFileOp != null) { try { await CopyDbAsync(assetFile, dbFileName); } catch (Exception) { // CopyDbAsync throws when the file already exists. } } } SQLite.Net.Interop.IDbHandle dbHandle; if (_sqliteAPI.Open(GetNullTerminatedUtf8(absoluteDbPath), out dbHandle, (int)sqlOpenFlags, IntPtr.Zero) == SQLite.Net.Interop.Result.OK) { _openDBs[dbFileName] = new OpenDB(dbHandle, absoluteDbPath); success.Invoke("Database opened"); } else { error.Invoke("Unable to open DB"); } }); }
public static Tuple <string, bool> base_name_for_Export(UIApplication uiapp, string source_path) { StringBuilder sb = new StringBuilder(); Application app = uiapp.Application; string final_hashed_base_name = ""; bool continueproc = true; //create base hash and folder name string target_hashed_folder = Helper.AndHash(source_path) + Path.GetFileNameWithoutExtension(source_path); //string target_hashed_folder = Path.GetDirectoryName(tmp); // TaskDialog.Show("x", target_hashed_folder + " "); string rvt_base_name = Path.GetFileNameWithoutExtension(source_path); string moved_rvt_path = FileManager.model_path + target_hashed_folder + ".rvt"; string moved_folder_path = FileManager.export_location + target_hashed_folder; bool rvt_exists_at_start = File.Exists(moved_rvt_path); bool folder_exists_at_start = File.Exists(moved_folder_path); if (rvt_exists_at_start == false) { sb.AppendLine("RVT already exists " + rvt_exists_at_start.ToString()); //check if exists by existing folder var mathing_DirsByBaseName = Directory.EnumerateDirectories(FileManager.export_location, "*" + rvt_base_name); //if the folder exists, does ---shell exsist? if (mathing_DirsByBaseName.Count() > 1) { string temp_file_path = FileManager.MoveAndRecord(source_path); sb.AppendLine("copying temp file and checking for sheet matches: " + temp_file_path); OpenOptions op = new OpenOptions(); op.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath( temp_file_path); UIDocument uidoc = uiapp.OpenAndActivateDocument(mp, op, false); Document doc = uidoc.Document; //doc.Save(); SaveAsOptions options = new SaveAsOptions(); options.OverwriteExistingFile = true; options.MaximumBackups = 1; doc.SaveAs(temp_file_path, options); List <ViewSheet> AllSheets = Helper.GetAllSheets(doc); if (AllSheets.Count() > 0) { sb.AppendLine("POssible matches exist : " + mathing_DirsByBaseName.Count().ToString()); bool found_match_in_possible_dirs = false; foreach (var possible_dir in mathing_DirsByBaseName) { var sheet_strings = AllSheets.Select(x => x.ViewName + " - Sheet - " + x.SheetNumber); var sheet_files = Directory.GetFiles(possible_dir); bool all_sheets_present = true; foreach (string sheet_string in sheet_strings) { var cl = sheet_strings.Where(x => x.Contains(sheet_string)).Count(); if (cl == 0) { all_sheets_present = false; break; } } if (all_sheets_present == true) { final_hashed_base_name = Path.GetFileName(possible_dir); found_match_in_possible_dirs = true; } } if (found_match_in_possible_dirs == false) { sb.AppendLine("Matches do did not have same sheets"); final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name; continueproc = true; UIDocument uidoc2 = uiapp.OpenAndActivateDocument(FileManager.init_path); doc.Close(); saveCentralProd(uiapp, temp_file_path, final_hashed_base_name); } else { sb.AppendLine("Match found with same sheets"); // final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name; UIDocument uidoc2 = uiapp.OpenAndActivateDocument(FileManager.init_path); doc.Close(); } } else { final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name; sb.AppendLine("No Sheets found..."); saveCentralProd(uiapp, temp_file_path, final_hashed_base_name); continueproc = false; } } else if (mathing_DirsByBaseName.Count() == 1) { final_hashed_base_name = Path.GetFileName(mathing_DirsByBaseName.First()); } else { //if no directory is found with the base_name - this was never exported... // use good hash, sb.AppendLine("No Directory found creating new..."); final_hashed_base_name = Helper.ConsHash(source_path) + rvt_base_name; } } else { //if folder is present, then it is base folder sb.AppendLine("Directory Exists " + final_hashed_base_name); final_hashed_base_name = Path.GetFileName(moved_folder_path); } sb.AppendLine(); //TaskDialog.Show("d", FileManager.export_location + final_hashed_base_name); string final_dir_path = FileManager.mkdir(FileManager.export_location + final_hashed_base_name); File.AppendAllText(final_dir_path + "\\log.txt", sb.ToString()); return(new Tuple <string, bool>(final_hashed_base_name, continueproc)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; WorksetConfiguration openConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); OpenOptions openOptions = new OpenOptions(); openOptions.SetOpenWorksetsConfiguration(openConfig); openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; SaveAsOptions wsaveAs = new SaveAsOptions(); WorksharingSaveAsOptions saveConfig = new WorksharingSaveAsOptions(); saveConfig.SaveAsCentral = true; wsaveAs.SetWorksharingOptions(saveConfig); wsaveAs.OverwriteExistingFile = true; SaveAsOptions saveAs = new SaveAsOptions(); saveAs.OverwriteExistingFile = true; destinationpath = ""; documents.Clear(); string date = DateTime.Now.ToString("dd/MM/yyyy"); int completed = 0; int failed = 0; var exportdialog = new RevitBatchExporter.Dialogs.ExportDialog(); var dialog = exportdialog.ShowDialog(); if (dialog != DialogResult.OK) { return(Result.Cancelled); } bool purge = exportdialog.PurgeCheckBox.Checked; bool removeCADlinks = exportdialog.RemoveCADLinksCheckBox.Checked; bool removeCADImports = exportdialog.RemoveCADImportsCheckBox.Checked; bool removeRVTlinks = exportdialog.RemoveRVTLinksCheckBox.Checked; bool removeSchedules = exportdialog.SchedulesCheckBox.Checked; bool ungroup = exportdialog.UngroupCheckBox.Checked; bool removesheets = exportdialog.SheetsCheckBox.Checked; bool removeviewsON = exportdialog.ViewsONSheetsCheckBox.Checked; bool removeviewsNOT = exportdialog.ViewsNotSheetsCheckBox.Checked; bool exportnwc = exportdialog.NWCCheckBox.Checked; bool exportifc = exportdialog.IFCCheckBox.Checked; bool removeallsheetsviews = false; if (removesheets && removeviewsON && removeviewsNOT) { removeallsheetsviews = true; removesheets = false; removeviewsON = false; removeviewsNOT = false; } string reason = exportdialog.IssueReasonTextBox.Text.TrimEnd().TrimStart(); string customdate = exportdialog.DateTextBox.Text.TrimEnd().TrimStart(); string nameprefix = exportdialog.PrefixTextBox.Text.TrimEnd().TrimStart(); string namesuffix = exportdialog.SuffixTextBox.Text.TrimEnd().TrimStart(); string debugmessage = ""; bool samepath = false; List <string[]> results = new List <string[]>(); foreach (string path in documents) { string destdoc = nameprefix + Path.GetFileName(path.Replace(".rvt", "")) + namesuffix + ".rvt"; if (File.Exists(destinationpath + destdoc)) { samepath = true; break; } string pathOnly = Path.GetDirectoryName(path) + "\\"; if (pathOnly == destinationpath) { samepath = true; break; } } if (samepath) { TaskDialog td = new TaskDialog("XPORT"); td.MainInstruction = "Some documents already exist in the destination path."; td.MainContent = "The files will be overritten, do you wish to continue?"; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel"); switch (td.Show()) { case TaskDialogResult.CommandLink1: break; case TaskDialogResult.CommandLink2: return(Result.Cancelled); default: return(Result.Cancelled); } } uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing); uiapp.Application.FailuresProcessing += FailureProcessor; DateTime start = DateTime.Now; foreach (string path in documents) { string[] result = new string[5]; if (!File.Exists(path)) { result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = "false"; result[2] = "false"; result[3] = "File Not Found"; result[4] = ""; results.Add(result); failed++; continue; } try { DateTime s1 = DateTime.Now; Document doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openOptions); Transaction t1 = new Transaction(doc, "XP"); t1.Start(); if (customdate != "") { date = customdate; } try { doc.ProjectInformation.LookupParameter("Model Issue Date").Set(date); } catch { }; try { doc.ProjectInformation.IssueDate = date; } catch { }; if (reason != "") { try { doc.ProjectInformation.LookupParameter("Model Issue Reason").Set(reason); } catch { } } if (removeCADlinks) { DeleteCADLinks(doc); } if (removeCADImports) { DeleteCADImports(doc); } if (removeRVTlinks) { DeleteRVTLinks(doc); } if (removeviewsNOT) { DeleteViewsNotOnSheets(doc); } if (removeviewsON) { DeleteViewsONSheets(doc); } if (removesheets) { DeleteSheets(doc); } if (removeallsheetsviews) { DeleteAllViewsSheets(doc); } if (removeSchedules) { DeleteSchedules(doc); } if (ungroup) { UngroupGroups(doc); } if (purge) { PurgeDocument(doc); } t1.Commit(); string docname = doc.Title; docname = docname.Replace("_detached", ""); if (docname.EndsWith(".rvt")) { docname = docname.Replace(".rvt", ""); } if (nameprefix != "") { docname = nameprefix + docname; } if (namesuffix != "") { docname = docname + namesuffix; } bool nwcexported = false; bool ifcexported = false; if (exportnwc) { nwcexported = ExportNWC(doc, destinationpath, docname); } if (exportifc) { ifcexported = ExportIFC(doc, destinationpath, docname); } try { if (doc.IsWorkshared) { doc.SaveAs(destinationpath + docname + ".rvt", wsaveAs); doc.Close(false); } else { doc.SaveAs(destinationpath + docname + ".rvt", saveAs); doc.Close(false); } } catch { doc.Close(false); } try { Directory.Delete(destinationpath + docname + "_backup", true); } catch { } try { Directory.Delete(destinationpath + "Revit_temp", true); } catch { } doc.Dispose(); completed++; DateTime e1 = DateTime.Now; int h = (e1 - s1).Hours; int m = (e1 - s1).Minutes; int s = (e1 - s1).Seconds; result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = nwcexported.ToString(); result[2] = ifcexported.ToString(); result[3] = "Completed"; result[4] = h.ToString() + ":" + m.ToString() + ":" + s.ToString(); results.Add(result); } catch (Exception e) { debugmessage = "\n" + "\n" + e.Message; result[0] = Path.GetFileName(path.Replace(".rvt", "")); result[1] = "false"; result[2] = "false"; result[3] = "Failed"; result[4] = ""; results.Add(result); failed++; } } uiapp.DialogBoxShowing -= OnDialogBoxShowing; uiapp.Application.FailuresProcessing -= FailureProcessor; DateTime end = DateTime.Now; int hours = (end - start).Hours; int minutes = (end - start).Minutes; int seconds = (end - start).Seconds; //TaskDialog.Show("Results", "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s" + debugmessage); TaskDialog rd = new TaskDialog("XPORT"); rd.MainInstruction = "Results"; rd.MainContent = "Exported to: " + destinationpath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s"; rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close"); rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details"); documents.Clear(); destinationpath = ""; switch (rd.Show()) { case TaskDialogResult.CommandLink1: return(Result.Succeeded); case TaskDialogResult.CommandLink2: var resultsdialog = new RevitBatchExporter.Dialogs.ResultsDialog(); foreach (string[] r in results) { var item = new ListViewItem(r); resultsdialog.ResultsView.Items.Add(item); } var rdialog = resultsdialog.ShowDialog(); return(Result.Succeeded); default: return(Result.Succeeded); } }
public void GenerateAndUploadPDFtoSharePoint(string RelativeUrl, string PatientId, ConsentType ConsentFormType) { DocumentConverterServiceClient client = null; try { string sourceFileName = null; byte[] sourceFile = null; client = OpenService("http://localhost:41734/Muhimbi.DocumentConverter.WebService/"); OpenOptions openOptions = new OpenOptions(); //** Specify optional authentication settings for the web page openOptions.UserName = ""; openOptions.Password = ""; // ** Specify the URL to convert openOptions.OriginalFileName = RelativeUrl; openOptions.FileExtension = "html"; //** Generate a temp file name that is later used to write the PDF to sourceFileName = Path.GetTempFileName(); File.Delete(sourceFileName); // ** Enable JavaScript on the page to convert. openOptions.AllowMacros = MacroSecurityOption.All; // ** Set the various conversion settings ConversionSettings conversionSettings = new ConversionSettings(); conversionSettings.Fidelity = ConversionFidelities.Full; conversionSettings.PDFProfile = PDFProfile.PDF_1_5; conversionSettings.Quality = ConversionQuality.OptimizeForOnScreen; // ** Carry out the actual conversion byte[] convertedFile = client.Convert(sourceFile, openOptions, conversionSettings); //try //{ SPSecurity.RunWithElevatedPrivileges(delegate() { using (var site = new SPSite(SiteUrl)) { using (var web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; var list = web.Lists.TryGetList(DocumentLibary); if (list != null) { var libFolder = list.RootFolder; var patientDetails = GetPatientDetail(PatientId, ConsentFormType.ToString()); if (patientDetails != null) { string fileName = ConsentFormType + patientDetails.MRHash + patientDetails.name + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; switch (ConsentFormType) { case ConsentType.Surgical: { fileName = "SUR_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.BloodConsentOrRefusal: { fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Cardiovascular: { fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Endoscopy: { fileName = "ENDO_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.OutsideOR: { fileName = "OUTSDE_OR_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PICC: { fileName = "PICC_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PlasmanApheresis: { fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } } if (libFolder.RequiresCheckout) { try { SPFile fileOld = libFolder.Files[fileName]; fileOld.CheckOut(); } catch { } } var spFileProperty = new Hashtable(); spFileProperty.Add("MR#", patientDetails.MRHash); spFileProperty.Add("Patient#", PatientId); spFileProperty.Add("Patient Name", patientDetails.name); spFileProperty.Add("DOB#", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(patientDetails.DOB)); spFileProperty.Add("Procedure Type", patientDetails.ProcedureName); spFileProperty.Add("Patient Information", patientDetails.name + " " + DateTime.Now.ToShortDateString()); SPFile spfile = libFolder.Files.Add(fileName, convertedFile, spFileProperty, true); list.Update(); if (libFolder.RequiresCheckout) { spfile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn); spfile.Publish("Publish Comment"); } } } web.AllowUnsafeUpdates = false; } } }); } finally { CloseService(client); } }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { // ** Only .docx, .xlsx or .pptx filea are accepted string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.docx"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to convert and watermark."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = Path.GetExtension(sourceFileName); // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = new ConversionSettings(); // ** Format must be the same as the input format. // ** Resolve by parsing the extension into OtputFormat enum. // ** Leading dot (.) must be removed to make the parsing work. string format = Path.GetExtension(sourceFileName).TrimStart(new char[] { '.' }); conversionSettings.Format = (OutputFormat)Enum.Parse(typeof(OutputFormat), format, true); conversionSettings.Fidelity = ConversionFidelities.Full; conversionSettings.Quality = ConversionQuality.OptimizeForPrint; // ** Get the list of watermarks to apply. conversionSettings.Watermarks = CreateWatermarks(); // ** Carry out the watermarking. Console.WriteLine("Watermarking file " + sourceFileName); byte[] watermarkedFile = client.ApplyWatermark(sourceFile, openOptions, conversionSettings); // ** Write the watermarked file back to the file system with. string destinationFileName = Path.GetDirectoryName(sourceFileName) + @"\" + Path.GetFileNameWithoutExtension(sourceFileName) + "_Watermarked." + conversionSettings.Format; using (FileStream fs = File.Create(destinationFileName)) { fs.Write(watermarkedFile, 0, watermarkedFile.Length); fs.Close(); } Console.WriteLine("File watermarked to " + destinationFileName); // ** Open the generated file Console.WriteLine("Opening result document."); Process.Start(destinationFileName); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } Console.ReadKey(); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Application app = uiapp.Application; int check = 0; Document openDoc = null; using (var formOpen = new FormOpenFile()) { formOpen.ShowDialog(); string fileName = formOpen.filePath; ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(fileName); OpenOptions optionDetach = new OpenOptions(); optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; openDoc = app.OpenDocumentFile(modelP, optionDetach); check += 1; if (formOpen.DialogResult == winForms.DialogResult.OK) { using (var form = new FormPickSheets()) { List <ViewSheet> collector = Helpers.CollectViewSheet(openDoc); foreach (ViewSheet vs in collector) { form.sheetNames.Add(vs.Name); form.sheetNumbers.Add(vs.SheetNumber); } List <ViewSheetSet> allViewSheets = Helpers.CollectViewSheetSets(openDoc); foreach (ViewSheetSet vs in allViewSheets) { form.dictSheetSetsNames.Add(vs.Name, Helpers.SheetInViewSheetsSets(vs)); } Dictionary <string, PrintSetting> printSetting = Helpers.GetPrintersSettings(openDoc); form.printSettings = printSetting.Keys.ToList(); form.ShowDialog(); if (form.DialogResult == winForms.DialogResult.Cancel) { return(Result.Cancelled); } string destination = @"C:\Temp\"; //TaskDialog.Show("result", Helpers.CollectViewSheet(openDoc)); List <ViewSheet> sheetList = Helpers.FindViewSheetByNumber(openDoc, form.pickedNumbers); PrintSetting chosenPrintSet = printSetting.Values.ElementAt(form.pickedPrintSet); foreach (ViewSheet sheet in sheetList) { try { ViewSet vs = Helpers.CreateViewset(openDoc, sheet.SheetNumber);//create a viewset with each view to be printed (only way to be able to set the file names) } catch { TaskDialog.Show("Error", "Can't create ViewSet"); } Helpers.PrintDrawingsFromList(openDoc, sheet, destination + form.prefix + sheet.SheetNumber + Helpers.SheetRevision(sheet) + ".pdf", chosenPrintSet); } openDoc.Close(false); check += -1; if (check == 0) { TaskDialog.Show("Result", "The pdfs will appear in the printer default folder (something like C:\\Users\\[your name]\\Documents)"); } else { TaskDialog.Show("Result", "Something went wrong"); } } } } return(Result.Succeeded); }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { // ** If nothing is specified then read the first PDF file from the current folder. string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to convert to PDF/A."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = "pdf"; // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = new ConversionSettings(); // ** Set output to PDF/A conversionSettings.PDFProfile = PDFProfile.PDF_A2B; // ** Specify output settings as we want to force post processing of files. OutputFormatSpecificSettings_PDF osf = new OutputFormatSpecificSettings_PDF(); osf.PostProcessFile = true; // ** We need to specify ALL values of an object, so use these for PDF/A osf.FastWebView = false; osf.EmbedAllFonts = true; osf.SubsetFonts = false; conversionSettings.OutputFormatSpecificSettings = osf; // ** Carry out the conversion. Console.WriteLine("Converting file " + sourceFileName + " to PDF/A."); byte[] convFile = client.ProcessChangesAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult(); // ** Write the converted file back to the file system with a PDF extension. string destinationFileName = Path.GetFileNameWithoutExtension(sourceFileName) + "_PDFA.pdf"; using (FileStream fs = File.Create(destinationFileName)) { fs.Write(convFile, 0, convFile.Length); fs.Close(); } Console.WriteLine("File converted to " + destinationFileName); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.doc*"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to convert and watermark."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = Path.GetExtension(sourceFileName); // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = new ConversionSettings(); conversionSettings.Fidelity = ConversionFidelities.Full; conversionSettings.Quality = ConversionQuality.OptimizeForPrint; // ** Get the list of watermarks to apply. conversionSettings.Watermarks = CreateWatermarks(); // ** Carry out the conversion. Console.WriteLine("Converting file " + sourceFileName); byte[] convFile = client.ConvertAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult(); // ** Write the converted file back to the file system with a PDF extension. string destinationFileName = Path.Combine(Path.GetDirectoryName(sourceFileName), Path.GetFileNameWithoutExtension(sourceFileName) + "." + conversionSettings.Format); using (FileStream fs = File.Create(destinationFileName)) { fs.Write(convFile, 0, convFile.Length); fs.Close(); } Console.WriteLine("File converted to " + destinationFileName); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } }
public Document OpenRevitDocument(string revitFileName) { Document doc = null; try { LogFileManager.AppendLog("Open Revit Document: " + revitFileName); BasicFileInfo basicFileInfo = BasicFileInfo.Extract(revitFileName); FileOpenOptions fileOpenOptions = projectSettings.UpgradeOptions.UpgradeVersionOpenOptions; if (basicFileInfo.IsWorkshared) { ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(revitFileName); OpenOptions openOptions = new OpenOptions(); openOptions.Audit = fileOpenOptions.Audit; if (fileOpenOptions.DetachAndPreserveWorksets) { openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; } IList <WorksetPreview> wsPreviews = new List <WorksetPreview>(); IList <WorksetId> worksetIds = new List <WorksetId>(); WorksetConfiguration wsConfiguration = new WorksetConfiguration(); try { wsPreviews = WorksharingUtils.GetUserWorksetInfo(modelPath); if (wsPreviews.Count > 0) { foreach (WorksetPreview wsPreview in wsPreviews) { worksetIds.Add(wsPreview.Id); } if (fileOpenOptions.OpenAllWorkset) { wsConfiguration.Open(worksetIds); } else { wsConfiguration.Close(worksetIds); } openOptions.SetOpenWorksetsConfiguration(wsConfiguration); } } catch (Exception ex) { LogFileManager.AppendLog("[Warning] Open Worksets", ex.Message); } doc = uiApp.Application.OpenDocumentFile(modelPath, openOptions); } else { doc = uiApp.Application.OpenDocumentFile(revitFileName); } } catch (Exception ex) { string message = ex.Message; LogFileManager.AppendLog("[Error] Open Revit Document", message); } return(doc); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //载入FourPlugin.dll UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; string copyFilePath; //储存文件夹路径 string temFilePath; //临时文件路径 bool isWorkshared; //当前文档是否开启工作共享 bool enoughRAM; //内存是否足够 bool enoughDiskSpace; //储存空间是否足够 bool purgeUnused; //是否清除未使用项 bool packageLinkingModels; //是否打包链接模型 bool clearLinkingModels; //是否清除链接 string fileFullName; #region 环境判断及初始化 copyFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + doc.Title + ".rvt"; temFilePath = Constants.TemFolder + @"\\temFile.rvt"; isWorkshared = doc.IsWorkshared; enoughRAM = true; enoughDiskSpace = GetHardDiskFreeSpace("C") > 1.5; #endregion #region 警告 if (!enoughRAM) { message += "内存不足,请关闭一些软件释放运行内存\r\n"; } if (!enoughDiskSpace) { message += "C盘临时空间不足,请关闭一些程序释放空间\r\n"; } if (string.IsNullOrEmpty(message)) { return(Result.Cancelled); } #endregion #region 模型打包 //分离中心文件 if (isWorkshared) { //同步 doc.SynchronizeWithCentral(new TransactWithCentralOptions(), new SynchronizeWithCentralOptions()); //创建临时文件 Document temDoc = uiapp.Application.NewProjectDocument(@"C:\ProgramData\Autodesk\RVT 2019\Templates\China\Construction-DefaultCHSCHS.rte"); temDoc.SaveAs(temFilePath); temDoc.Close(false); uiapp.OpenAndActivateDocument(temFilePath); temDoc = uiapp.ActiveUIDocument.Document; //关闭本地文件 string docPathName = doc.PathName; ModelPath modelPath = doc.GetWorksharingCentralModelPath(); doc.Close(false); //分离模型 OpenOptions openOptions = new OpenOptions { DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets }; Document detachDoc = uiapp.Application.OpenDocumentFile(modelPath, openOptions); detachDoc.SaveAs(copyFilePath); detachDoc.Close(true); //重新打开本地文件 uiapp.OpenAndActivateDocument(docPathName); //清理临时文件 temDoc.Close(false); File.Delete(temFilePath); } else { doc.Save(); File.Copy(doc.PathName, copyFilePath); } #endregion return(Result.Succeeded); }
/// <summary> /// User coroutine to update UI during processing. /// </summary> public IEnumerator Upload(string directory, Guid accountId, Guid projectId, ObservableCollection <MigrationRule> modelRules) { var view = (ViewMigrationToBim360)View; if (!Directory.Exists(directory)) { view.UpdateUploadingProgress("Directory doesn't exist.", 0); yield break; } view.UpdateUploadingProgress("Ready to start.", 2); var models = Directory.GetFiles(directory, "*.rvt", SearchOption.AllDirectories); var count = 0; var ops = new OpenOptions { OpenForeignOption = OpenForeignOption.DoNotOpen, DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets }; // Open all documents and analyze if document has links. // If so, save the relationship info into "mapLocalModelPathToLinksName" var mapLocalModelPathToLinksName = new Dictionary <string, List <string> >(); foreach (var model in models) { var name = Path.GetFileName(model); var progress = count++ *100 / models.Length; var modelpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(model); view.UpdateUploadingProgress($"Analyzing {name}", progress); yield return(null); try { var doc = Application.Application.OpenDocumentFile(modelpath, ops); var links = new List <string>(); foreach (var linkInstance in GetLinkInstances(doc)) { links.Add(linkInstance.Name); } if (links.Count > 0) { mapLocalModelPathToLinksName[model] = links; } doc.Close(false); } catch (Exception e) { var msg = $"Failed to analyze {name} - {e.Message}"; view.UpdateUploadingProgress(msg, progress); MessageBox.Show(msg); yield break; } yield return(null); } // All link info should be dump to local file in case something wrong happens during uploading process JavaScriptSerializer serializer = new JavaScriptSerializer(); var jsonString = serializer.Serialize(mapLocalModelPathToLinksName); File.WriteAllText(FLinksInfo, jsonString); view.UpdateUploadingProgress("Analyzing finished", 100); // Begin Uploading count = 0; var mapModelsNameToGuid = new Dictionary <string, string>(); foreach (var model in models) { var name = Path.GetFileName(model); var progress = count++ *100 / models.Length; var modelpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(model); view.UpdateUploadingProgress($"Uploading {name}", progress); yield return(null); try { var doc = Application.Application.OpenDocumentFile(modelpath, ops); var folderUrn = GetTargetFolderUrn(modelRules, directory, model)?.Urn; doc.SaveAsCloudModel(accountId, projectId, folderUrn, $"Migrated_{Path.GetFileName(model)}"); var modelPath = doc.GetCloudModelPath(); mapModelsNameToGuid.Add(name, $"{modelPath.GetProjectGUID()},{modelPath.GetModelGUID()}"); doc.Close(false); } catch (Exception e) { var msg = $"Failed to upload {name} - {e.Message}"; view.UpdateUploadingProgress(msg, progress); MessageBox.Show(msg); yield break; } yield return(null); } jsonString = serializer.Serialize(mapModelsNameToGuid); File.WriteAllText(FModelsGuid, jsonString); view.UpdateUploadingProgress("Uploading finished", 100); }
public Document OpenNewLocalFromModelPath(ModelPath centralPath, ModelPath localPath, List <string> InverseWorksetList, out bool isWrkShared) { List <WorksetId> worksetsToOpen = new List <WorksetId>(); // First set to close all worksets WorksetConfiguration worksetConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets); OpenOptions theOpenOptions = new OpenOptions(); try { // Create the new local at the given path WorksharingUtils.CreateNewLocal(centralPath, localPath); // Select specific worksets to open // Get a list of worksets from the unopened document IList <WorksetPreview> worksets = WorksharingUtils.GetUserWorksetInfo(localPath); foreach (WorksetPreview preview in worksets) { bool Include = true; // The inverse list is the inverse of the worksets checked. In other // words an exclusion list. foreach (string ws in InverseWorksetList) { if (ws == "") { continue; } if (preview.Name.StartsWith(ws)) { Include = false; continue; } else { } } if (Include) { worksetsToOpen.Add(preview.Id); } else { //System.Windows.MessageBox.Show("Excluding " + preview.Name); } } // Setup option to open the target worksets // then set specific ones to open worksetConfig.Open(worksetsToOpen); theOpenOptions.SetOpenWorksetsConfiguration(worksetConfig); // Now open the new local Document openedDoc = _app.OpenDocumentFile(localPath, theOpenOptions); isWrkShared = true; return(openedDoc); } catch (Exception ex) { System.Windows.MessageBox.Show("Opening the file from its location.\n\n" + ex.Message, "This Is Not A Workshared File"); } // If here then not a workshared file. string fname = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath); Document openedDocN = _app.OpenDocumentFile(fname); isWrkShared = false; return(openedDocN); }
/// <summary> /// Try to open each cloud model and reload if they have links, /// making that point to cloud path. /// </summary> /// <param name="directory">Transit directory where cloud models exist</param> /// <param name="projectId">not used</param> /// <returns></returns> public IEnumerator ReloadLinks(string directory, Guid projectId) { var view = (ViewMigrationToBim360)View; if (!Directory.Exists(directory)) { view.UpdateReloadingProgress("Directory doesn't exist.", 0); yield break; } view.UpdateReloadingProgress("Ready to start.", 2); var ops = new OpenOptions(); var transOp = new TransactWithCentralOptions(); var swcOptions = new SynchronizeWithCentralOptions(); var count = 0; // Read mapping info var jsonString = File.ReadAllText(FLinksInfo); JavaScriptSerializer serializer = new JavaScriptSerializer(); var mapLocalModelPathToLinksName = serializer.Deserialize <Dictionary <string, List <string> > >(jsonString); jsonString = File.ReadAllText(FModelsGuid); var mapModelsNameToGuid = serializer.Deserialize <Dictionary <string, string> >(jsonString); // Try to open each cloud model and reload if they have links, making that point to cloud path. foreach (var kvp in mapLocalModelPathToLinksName) { var localPath = kvp.Key; var name = Path.GetFileName(localPath); var guids = mapModelsNameToGuid[name].Split(','); var hostModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath("US", Guid.Parse(guids[0]), Guid.Parse(guids[1])); var progress = count++ *100 / mapLocalModelPathToLinksName.Count(); view.UpdateReloadingProgress($"Reloading {name}", progress); yield return(null); try { var doc = Application.Application.OpenDocumentFile(hostModelPath, ops, new DefaultOpenFromCloudCallback()); foreach (var linkInstance in GetLinkInstances(doc)) { if (mapModelsNameToGuid.TryGetValue(linkInstance.Name, out var sLinkedGuids)) { guids = mapModelsNameToGuid[linkInstance.Name].Split(','); var linkModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath("US", Guid.Parse(guids[0]), Guid.Parse(guids[1])); linkInstance.LoadFrom(linkModelPath, new WorksetConfiguration()); } } doc.SynchronizeWithCentral(transOp, swcOptions); doc.Close(false); } catch (Exception e) { var msg = $"Failed to reload {name} - {e.Message}"; view.UpdateUploadingProgress(msg, progress); MessageBox.Show(msg); yield break; } } view.UpdateReloadingProgress("Reloading finished", 100); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var doc = commandData.Application.ActiveUIDocument.Document; var log = new StringBuilder( "Имя семейства;ADSK_Наименование;ADSK_Марка;ADSK_Код изделия;ADSK_Завод-изготовитель;ADSK_Единица измерения;ADSK_Количество;ADSK_Масса\n"); if (CheckOpenedFamilies(doc)) { var fPath = SelectFolder(); if (fPath.Equals("")) { return(Result.Cancelled); } var logFile = Path.Combine(fPath, "Log_ADSK_Checker.csv"); var lFiles = new List <string>(); var lFilesBck = new List <string>(); var files = Directory.GetFiles(fPath, "*.rfa", SearchOption.AllDirectories); lFiles.AddRange(files); var filesBck = Directory.GetFiles(fPath, "*.????.rfa", SearchOption.AllDirectories); lFilesBck.AddRange(filesBck); if (files.Length > 0) { foreach (var fl in lFiles) { if (lFilesBck.Contains(fl)) { continue; } var mPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(fl); var oOps = new OpenOptions { Audit = true }; var famDoc = doc.Application.OpenDocumentFile(mPath, oOps); var fam = famDoc.OwnerFamily; if (fam.FamilyCategory.CategoryType == CategoryType.Model) { var rfaName = Path.GetFileName(fl); log.AppendLine(rfaName + CheckFamily(famDoc)); } famDoc.Close(false); } } var text = log.ToString().Replace(';', '\t'); using (var sWriter = new StreamWriter(logFile, false, Encoding.GetEncoding("windows-1251"))) { sWriter.Write(text); } var td = new TaskDialog("Check_Family") { Id = "ID_TaskDialog_Checked_Families", MainIcon = TaskDialogIcon.TaskDialogIconWarning, Title = "Проверка файлов семейств", TitleAutoPrefix = false, AllowCancellation = true, MainInstruction = "Семейства проверены, файл отчет находится в корневой папке поиска" }; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "ОК"); td.Show(); } else { var td = new TaskDialog("Warn_Families") { Id = "ID_TaskDialog_Warn_Families", MainIcon = TaskDialogIcon.TaskDialogIconWarning, Title = "Проверка файлов семейств", TitleAutoPrefix = false, AllowCancellation = true, MainInstruction = "Перед пакетной проверкой семейств необходимо закрыть все текущие открытые семейства!" }; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "ОК"); td.Show(); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document mainDoc = commandData.Application.ActiveUIDocument.Document; Application revitApp = commandData.Application.Application; //открываю окно выбора параметров, которые буду заполняться FormSelectParams formSelectParams = new FormSelectParams(); formSelectParams.ShowDialog(); if (formSelectParams.DialogResult != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } RebarDocumentWorker mainWorker = new RebarDocumentWorker(); List <Element> mainDocConcreteElements = new List <Element>(); string mainWorkerMessage = mainWorker.Start(mainDoc, revitApp, Transform.Identity, out mainDocConcreteElements); if (!string.IsNullOrEmpty(mainWorkerMessage)) { message = mainWorkerMessage + ". Документ " + mainDoc.Title; return(Result.Failed); } if (Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.NoLinks) { return(Result.Succeeded); } List <RevitLinkInstance> linksAll = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .ToList(); List <RevitLinkInstance> linksLib = linksAll .Where(i => i.Name.Contains(".lib")) .ToList(); // имя ссылки lib и список конструкций, которые она пересекает Dictionary <string, List <Element> > hostElemsForLibLinks = new Dictionary <string, List <Element> >(); foreach (RevitLinkInstance rli in linksLib) { string linkInstanceTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli); Element hostElem = LinksSupport.GetConcreteElementIsHostForLibLinkFile(mainDoc, ViewSupport.GetDefaultView(mainDoc), mainDocConcreteElements, rli); if (hostElem == null) { continue; } if (hostElemsForLibLinks.ContainsKey(linkInstanceTitle)) { hostElemsForLibLinks[linkInstanceTitle].Add(hostElem); } else { hostElemsForLibLinks.Add(linkInstanceTitle, new List <Element> { hostElem }); } } List <RevitLinkInstance> linksWithoutDuplicates = LinksSupport.DeleteDuplicates(linksAll); foreach (RevitLinkInstance rli in linksWithoutDuplicates) { RevitLinkType rlt = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType; Document linkDoc = rli.GetLinkDocument(); if (linkDoc == null) { continue; } string linkDocTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli); if (!linkDocTitle.Contains("-КР-")) { continue; } if (!linkDocTitle.Contains("lib") && Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.OnlyLibs) { continue; } ModelPath mPath = linkDoc.GetWorksharingCentralModelPath(); rlt.Unload(new SaveCoordinates()); OpenOptions oo = new OpenOptions(); linkDoc = revitApp.OpenDocumentFile(mPath, oo); RebarDocumentWorker linkWorker = new RebarDocumentWorker(); if (linkDocTitle.Contains("lib")) { if (hostElemsForLibLinks.ContainsKey(linkDocTitle)) { List <Element> mainElemsForLib = hostElemsForLibLinks[linkDocTitle]; if (mainElemsForLib.Count > 0) { linkWorker.MainElementsForLibFile = mainElemsForLib; } } } Transform linkTransform = rli.GetTransform(); List <Element> linkConcreteElements = new List <Element>(); string linkWorkerMessage = linkWorker.Start(linkDoc, revitApp, linkTransform, out linkConcreteElements); if (!string.IsNullOrEmpty(linkWorkerMessage)) { message = linkWorkerMessage + ". Связь " + linkDoc.Title; return(Result.Failed); } TransactWithCentralOptions transOpt = new TransactWithCentralOptions(); SynchronizeWithCentralOptions syncOpt = new SynchronizeWithCentralOptions(); RelinquishOptions relOpt = new RelinquishOptions(true); syncOpt.SetRelinquishOptions(relOpt); linkDoc.SynchronizeWithCentral(transOpt, syncOpt); linkDoc.Close(); #if R2017 RevitLinkLoadResult rllr = rlt.Reload(); #else LinkLoadResult llr = rlt.Reload(); #endif } return(Result.Succeeded); }
public void GenerateAndUploadPdFtoSharePoint(string relativeUrl, string patientId, ConsentType consentFormType, string location) { DocumentConverterServiceClient client = null; try { // creating the folder if it is not exits in the drive. var folderPath = GetPdFFolderPath(consentFormType); if (!string.IsNullOrEmpty(folderPath)) { byte[] sourceFile = null; client = OpenService("http://localhost:41734/Muhimbi.DocumentConverter.WebService/"); var openOptions = new OpenOptions { UserName = "", Password = "", OriginalFileName = relativeUrl, FileExtension = "html", AllowMacros = MacroSecurityOption.All }; // ** Set the various conversion settings var conversionSettings = new ConversionSettings { Fidelity = ConversionFidelities.Full, PDFProfile = PDFProfile.PDF_1_5, Quality = ConversionQuality.OptimizeForOnScreen }; // ** Carry out the actual conversion byte[] convertedFile = client.Convert(sourceFile, openOptions, conversionSettings); var patientDetails = GetPatientDetail(patientId, consentFormType.ToString(), location); string fileName = consentFormType + patientDetails.MRHash + patientDetails.name + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; switch (consentFormType) { case ConsentType.Surgical: { fileName = "SUR_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.BloodConsentOrRefusal: { fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Cardiovascular: { fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Endoscopy: { fileName = "ENDO_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.OutsideOR: { fileName = "OUTSDE_OR_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PICC: { fileName = "PICC_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PlasmanApheresis: { fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } } if (!new Uri(folderPath).IsUnc) { CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "Generating in local folder"); if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); fileName = Path.Combine(folderPath, fileName); File.WriteAllBytes(fileName, convertedFile); } else { var credentials = GetPdFPathCredentials(); if (credentials != null) { using (var unc = new UNCAccessWithCredentials()) { unc.NetUseDelete(); if (unc.NetUseWithCredentials(folderPath, credentials.Username.Trim(), credentials.Domain.Trim(), credentials.Password.Trim())) { if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); fileName = Path.Combine(folderPath, fileName); File.WriteAllBytes(fileName, convertedFile); } else { CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "Not able to connect the UNC path with the given credentials using [" + folderPath + "],[" + credentials.Domain.Trim() + "],[" + credentials.Username.Trim() + "],[" + credentials.Password.Trim() + "]"); } } } else { CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "The export credentials not found."); } } /* //try //{ SPSecurity.RunWithElevatedPrivileges(delegate() { using (var site = new SPSite(SiteUrl)) { using (var web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; var list = web.Lists.TryGetList(DocumentLibary); if (list != null) { var libFolder = list.RootFolder; var patientDetails = GetPatientDetail(PatientId, ConsentFormType.ToString()); if (patientDetails != null) { string fileName = ConsentFormType + patientDetails.MRHash + patientDetails.name + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; switch (ConsentFormType) { case ConsentType.Surgical: { fileName = "SUR_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.BloodConsentOrRefusal: { fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Cardiovascular: { fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.Endoscopy: { fileName = "ENDO_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.OutsideOR: { fileName = "OUTSDE_OR_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PICC: { fileName = "PICC_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } case ConsentType.PlasmanApheresis: { fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf"; break; } } if (libFolder.RequiresCheckout) { try { SPFile fileOld = libFolder.Files[fileName]; fileOld.CheckOut(); } catch { } } var spFileProperty = new Hashtable(); spFileProperty.Add("MR#", patientDetails.MRHash); spFileProperty.Add("Patient#", PatientId); spFileProperty.Add("Patient Name", patientDetails.name); spFileProperty.Add("DOB#", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(patientDetails.DOB)); spFileProperty.Add("Procedure Type", patientDetails.ProcedureName); spFileProperty.Add("Patient Information", patientDetails.name + " " + DateTime.Now.ToShortDateString()); SPFile spfile = libFolder.Files.Add(fileName, convertedFile, spFileProperty, true); list.Update(); if (libFolder.RequiresCheckout) { spfile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn); spfile.Publish("Publish Comment"); } } } web.AllowUnsafeUpdates = false; } } }); */ } else { CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "The folder path not found."); } } catch (Exception ex) { CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", ex.Message + "," + ex.StackTrace); } finally { CloseService(client); } }
public async void should_download_with_range_header() { var documentHandle = DocumentHandle.FromString("Pdf_2"); await _documentStoreClient.UploadAsync( TestConfig.PathToDocumentPdf, documentHandle ); // waits for storage await UpdateAndWaitAsync(); var format = new DocumentFormat("original"); var options = new OpenOptions() { FileName = "pluto.pdf", RangeFrom = 0, RangeTo = 199 }; var reader = _documentStoreClient.OpenRead(documentHandle, format, options); using (var downloaded = new MemoryStream()) { await (await reader.OpenStream()).CopyToAsync(downloaded); Assert.AreEqual(200, downloaded.Length, "Wrong range support"); Assert.AreEqual(200, reader.ContentLength); Assert.AreEqual("bytes 0-199/72768", reader.ReponseHeaders[HttpResponseHeader.ContentRange]); } //load without rangeto options = new OpenOptions() { FileName = "pluto.pdf", RangeFrom = 200 }; reader = _documentStoreClient.OpenRead(documentHandle, format, options); using (var downloaded = new MemoryStream()) { await (await reader.OpenStream()).CopyToAsync(downloaded); Assert.AreEqual(72768 - 200, downloaded.Length, "Wrong range support"); Assert.AreEqual(72768 - 200, reader.ContentLength); Assert.AreEqual("bytes 200-72767/72768", reader.ReponseHeaders[HttpResponseHeader.ContentRange]); } }
private void ProcessSelection(string selectedFilePathName) { string runningMsg; if (selectedFilePathName != null) { if ((bool)chkInfoOnly.IsChecked) { try { RevitFileSniffer rfs = new RevitFileSniffer(selectedFilePathName); rfs.ReportRevitInfo(); } catch (Exception ex) { string ms = "\n\nDo you must have this file open? The sniffer cannot snif if it's open."; System.Windows.MessageBox.Show(ex.Message + ms, "Error At RevitFileSniffer"); } return; } Hide(); FormMsgWPF HUD = new FormMsgWPF(); string FileToOpen = selectedFilePathName; try { OpenOptions op = new OpenOptions(); op.SetOpenWorksetsConfiguration(null); // makes all worksets opened? op.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach; ModelPath mdlPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(FileToOpen); string fName = System.IO.Path.GetFileNameWithoutExtension(FileToOpen); string fext = System.IO.Path.GetExtension(FileToOpen); string UserInitials = Environment.UserName.ToString(); fName = fName + "_" + UserInitials + fext; runningMsg = selectedFilePathName + " for " + UserInitials; HUD.SetMsg(runningMsg, "Processing for " + UserInitials); HUD.Show(); string source = FileToOpen; string[] stringSeparators = new string[] { "\\" }; var result = source.Split(stringSeparators, StringSplitOptions.None); string localPrjPath = string.Empty; string fullLFname = string.Empty; ModelPath localPath = null; try { if (result.Length > 4) { localPrjPath = _locRevitRoot + "\\" + result[3] + "_" + UserInitials + "\\"; fullLFname = localPrjPath + fName; //MessageBox.Show(fullLFname, "First Pass Local Path"); localPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(fullLFname); } else { HUD.Close(); System.Windows.MessageBox.Show("Based on its location, the file selected does not look like a project file .\n\n" + FileToOpen, "Not Touching This Without A Ten Foot Pole"); Close(); return; } #region Check For Open Document DocumentSet ds = _uiapp.Application.Documents; foreach (Document d in ds) { String dF = d.PathName.Replace(@"\\SYSFILE\CADD", "J:"); if (fullLFname.ToUpper().Equals(dF.ToUpper())) { string msg = "You have " + selectedFilePathName + " already open"; msg = msg + " or it is linked to a file you have open. Either way"; msg = msg + " Revit will not let you open it until the other one is unloaded."; System.Windows.MessageBox.Show(msg, "Sorry, You Cannot Open The File"); HUD.Close(); Close(); return; } } #endregion if (!Directory.Exists(localPrjPath)) { try { runningMsg = runningMsg + "\n\nCreated Local Folder: " + localPrjPath; HUD.SetMsg(runningMsg, "Creating This Local Folder"); Directory.CreateDirectory(localPrjPath); } catch (Exception ex) { HUD.Close(); System.Windows.MessageBox.Show(localPrjPath + "\n\n" + ex.Message, "Error Creating Directory"); Close(); return; } } else { runningMsg = runningMsg + "\n\nUsing Local Folder: " + localPrjPath; HUD.SetMsg(runningMsg, "Using This Local Folder"); } } catch (Exception) { HUD.Close(); System.Windows.MessageBox.Show("Error: Did Not Create " + localPrjPath, "Debug"); Close(); return; } #region Handle any existing local file if (File.Exists(fullLFname)) { string StashFolder = localPrjPath + "PriorsStash\\"; runningMsg = runningMsg + "\n\nStashing Older Local File To: " + StashFolder; HUD.SetMsg(runningMsg, "Stashing Older Local File To"); if (!Directory.Exists(StashFolder)) { try { Directory.CreateDirectory(StashFolder); } catch (Exception ex) { HUD.Close(); System.Windows.MessageBox.Show(StashFolder + "\n\n" + ex.Message, "Error Creating Directory"); Close(); return; } } string OrgFNameWOExt = System.IO.Path.GetFileNameWithoutExtension(fullLFname); string ext = System.IO.Path.GetExtension(fullLFname); string NewFNameWExt = AssignNewUniqueFileName(StashFolder + OrgFNameWOExt + ext); try { File.Move(fullLFname, NewFNameWExt); int qtyDeleted = LimitNumberOfStashedFiles(StashFolder + OrgFNameWOExt + ext, stashMax); if (qtyDeleted > 0) { runningMsg = runningMsg + "\n\nTrashed " + qtyDeleted.ToString() + " stashed older file" + pluralOrNot(qtyDeleted) + " from the PriorsStash folder."; } } catch (Exception ex) { HUD.Close(); System.Windows.MessageBox.Show(fullLFname + "\nto\n" + NewFNameWExt + "\n\n" + ex.Message, "File Error Moving File"); Close(); return; } string backupFldr = localPrjPath + OrgFNameWOExt + "_backup"; if (Directory.Exists(backupFldr)) { try { runningMsg = runningMsg + "\n\nTrashing Older Backup Folder: " + backupFldr; HUD.SetMsg(runningMsg, "Trashing Older Backup Folder"); Directory.Delete(backupFldr, true); } catch (Exception ex) { HUD.Close(); System.Windows.MessageBox.Show(backupFldr + "\n\n" + ex.Message, "Error Deleting Backup Folder"); Close(); return; } } } #endregion runningMsg = runningMsg + "\n\nLocal Document Is: " + fullLFname; /////runningMsg = runningMsg + "\n\n" + ExcludeTheseMsg(); HUD.SetMsg(runningMsg, "Revit Is Opening This Document For " + UserInitials); HUD.UpdateLayout(); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); HUD.Close(); SetStatusBarText(_revitHandle, "Just guessing that maybe you actually think something is happening."); #region Finally Create and Open Autodesk.Revit.UI.UIDocument newUIDoc = null; if (mdlPath != null || localPath != null) { AKSOpenUtils AKSOpen = new AKSOpenUtils(_uiapp, revVersion); // MessageBox.Show(fullLFname, "Will OpenNewLocalFromModelPath"); PokeRevit(); newUIDoc = AKSOpen.DoOpenNewLocalFromModelPath(mdlPath, localPath); } #endregion adWin.ComponentManager.Ribbon.Visibility = System.Windows.Visibility.Visible; } catch (Exception ex) { HUD.Close(); System.Windows.MessageBox.Show(ex.Message + " | " + ex.InnerException.Message, "Where is this Bummer"); Close(); return; } UpDateRecentsList(FileToOpen); Close(); } }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { //** Delete any split files from a previous test run. foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory(), "spf-*.pdf")) { File.Delete(file); } // ** If nothing is specified then read the first PDF file from the current folder. string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to split."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = "pdf"; // ** Set the absolute minimum conversion settings. ConversionSettings conversionSettings = new ConversionSettings(); // ** Create the ProcessingOptions for the splitting task. ProcessingOptions processingOptions = new ProcessingOptions() { MergeSettings = null, SplitOptions = new FileSplitOptions() { FileNameTemplate = "spf-{0:D3}", FileSplitType = FileSplitType.ByNumberOfPages, BatchSize = 5, BookmarkLevel = 0 }, SourceFiles = new SourceFile[1] { new SourceFile() { MergeSettings = null, OpenOptions = openOptions, ConversionSettings = conversionSettings, File = sourceFile } } }; // ** Carry out the splittng. Console.WriteLine("Splitting file " + sourceFileName); BatchResults batchResults = client.ProcessBatch(processingOptions); // ** Process the returned files foreach (BatchResult result in batchResults.Results) { Console.WriteLine("Writing split file " + result.FileName); File.WriteAllBytes(result.FileName, result.File); } Console.WriteLine("Finished."); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } Console.ReadKey(); }
/// <summary> /// Main application logic /// Executes on "ok" click /// opens selected files, audits them, and saves then closes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOk_Click(object sender, RoutedEventArgs e) { // Guard Condition if (filePaths.Length == 0) { Close(); } // Setup progress bar animation progressBar.IsIndeterminate = false; progressBar.Maximum = filePaths.Length; progressBar.Minimum = 0; // required stateful variables for tracking progress int numComplete = 0; int numRemaining = filePaths.Length; bool backupUndeleted = false; IList <string> problemFiles = new List <string>(); // create a timer to show time remaining Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (int i = 0; i < filePaths.Length; i++) { string path = filePaths[i]; secondsRemaining = TimeLeft(stopWatch, numComplete, numRemaining); // Update Progress progressBar.Dispatcher.Invoke(new ProgressBarDelegate(UpdateProgress), System.Windows.Threading.DispatcherPriority.Background); // Process files try { // Set the "audit on open" option to true OpenOptions opts = new OpenOptions(); if (checkAudit.IsChecked == true) { opts.Audit = true; } // Convert the string filepath to a ModelPath ModelPath mPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path); // Open the model (initiating upgrade and audit) Document doc = _commandData.Application.Application.OpenDocumentFile(mPath, opts); // Save and close the model doc.Close(true); // Update counters numComplete++; numRemaining--; // Delete the backup file try { string[] splitPath = path.Split('.'); string newPath = ""; for (int j = 0; j < splitPath.Length - 1; j++) { newPath += splitPath[j] + "."; } newPath += "0001." + splitPath.Last(); File.Delete(newPath); } catch (DirectoryNotFoundException) { backupUndeleted = true; continue; } } catch (Exception) { string fileName = path.Split('\\').Last(); problemFiles.Add(fileName); continue; } } stopWatch.Stop(); TaskDialog.Show("AutoAudit", "All audits and upgrades complete!"); // Show any files that could not be processed or deleted if (backupUndeleted) { problemFiles.Add("Some backups could not be deleted"); } if (problemFiles.Count != 0) { ErrorWindow errWindow = new ErrorWindow(problemFiles); errWindow.ShowDialog(); } // Return control to main application Close(); }
static void Main(string[] args) { DocumentConverterServiceClient client = null; try { // ** Determine the source file and read it into a byte array. string sourceFileName = null; if (args.Length == 0) { // ** If nothing is specified then read the first PDF file from the current folder. string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf"); if (sourceFiles.Length > 0) { sourceFileName = sourceFiles[0]; } else { Console.WriteLine("Please specify a document to extract data from."); Console.ReadKey(); return; } } else { sourceFileName = args[0]; } byte[] sourceFile = File.ReadAllBytes(sourceFileName); // ** Open the service and configure the bindings client = OpenService(SERVICE_URL); //** Set the absolute minimum open options OpenOptions openOptions = new OpenOptions(); openOptions.OriginalFileName = Path.GetFileName(sourceFileName); openOptions.FileExtension = "pdf"; // ** Set the absolute minimum conversion settings // ** and set output format to XFDF ConversionSettings conversionSettings = new ConversionSettings(); conversionSettings.Fidelity = ConversionFidelities.Full; conversionSettings.Format = OutputFormat.XFDF; // ** Carry out the conversion. Console.WriteLine("Exporting data from file " + sourceFileName + " to XFDF."); byte[] convFile = client.ConvertAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult(); // ** Write the converted file back to the file system with a PDF extension. string destinationFileName = Path.GetFileNameWithoutExtension(sourceFileName) + ".xfdf"; using (FileStream fs = File.Create(destinationFileName)) { fs.Write(convFile, 0, convFile.Length); fs.Close(); } Console.WriteLine("Data exported to " + destinationFileName); } catch (FaultException <WebServiceFaultException> ex) { Console.WriteLine("FaultException occurred: ExceptionType: " + ex.Detail.ExceptionType.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { CloseService(client); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Listeners.Clear(); Debug.Listeners.Add(new RbsLogger.Logger("BatchPrint")); Debug.WriteLine("Print started"); App.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location; Selection sel = commandData.Application.ActiveUIDocument.Selection; Document mainDoc = commandData.Application.ActiveUIDocument.Document; string mainDocTitle = SheetSupport.GetDocTitleWithoutRvt(mainDoc.Title); YayPrintSettings printSettings = YayPrintSettings.GetSavedPrintSettings(); printSettings.dwgProfiles = DwgSupport.GetAllDwgExportSettingsNames(mainDoc); //листы из всех открытых файлов, ключ - имя файла, значение - список листов Dictionary <string, List <MySheet> > allSheets = SheetSupport.GetAllSheets(commandData, printSettings); //получаю выбранные листы в диспетчере проекта List <ElementId> selIds = sel.GetElementIds().ToList(); //List<MySheet> mSheets0 = new List<MySheet>(); bool sheetsIsChecked = false; foreach (ElementId id in selIds) { Element elem = mainDoc.GetElement(id); ViewSheet sheet = elem as ViewSheet; if (sheet == null) { continue; } sheetsIsChecked = true; MySheet sheetInBase = allSheets[mainDocTitle].Where(i => i.sheet.Id.IntegerValue == sheet.Id.IntegerValue).First(); sheetInBase.IsPrintable = true; //mSheets0.Add(new MySheet(sheet)); } if (!sheetsIsChecked) { message = "Не выбраны листы. Выберите листы в Диспетчере проекта через Shift."; Debug.WriteLine("Печать остановлена, не выбраны листы"); return(Result.Failed); } //запись статистики по файлу //ProjectRating.Worker.Execute(commandData); //очистка старых Schema при необходимости /*try * { * Autodesk.Revit.DB.ExtensibleStorage.Schema sch = * Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD4")); * Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch, true); * * Autodesk.Revit.DB.ExtensibleStorage.Schema sch2 = * Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD5")); * Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch2, true); * Debug.WriteLine("Schema очищены"); * } * catch * { * Debug.WriteLine("Не удалось очистить Schema"); * } */ FormPrint form = new FormPrint(allSheets, printSettings); form.ShowDialog(); if (form.DialogResult != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } Debug.WriteLine("В окне печати нажат ОК, переход к печати"); printSettings = form.printSettings; string printerName = printSettings.printerName; allSheets = form.sheetsSelected; Debug.WriteLine("Выбранные для печати листы"); foreach (var kvp in allSheets) { Debug.WriteLine(" Файл " + kvp.Key); foreach (MySheet ms in kvp.Value) { Debug.WriteLine(" Лист " + ms.sheet.Name); } } string outputFolderCommon = printSettings.outputFolder; YayPrintSettings.SaveSettings(printSettings); Debug.WriteLine("Настройки печати сохранены"); //Дополнительные возможности работают только с PDFCreator if (printerName != "PDFCreator") { if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs || printSettings.useOrientation) { string errmsg = "Объединение PDF и печать \"Штампа\" в цвете поддерживаются только для PDFCreator."; errmsg += "\nВо избежание ошибок эти настройки будут отключены."; TaskDialog.Show("Предупреждение", errmsg); printSettings.mergePdfs = false; printSettings.excludeColors = new List <PdfColor>(); printSettings.useOrientation = false; Debug.WriteLine("Выбранные настройки несовместимы с принтером " + printerName); } } else { if (!printSettings.useOrientation) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Automatic); Debug.WriteLine("Установлена ориентация листа Automatic"); } } bool printToFile = form.printToFile; string outputFolder = ""; if (printToFile) { outputFolder = PrintSupport.CreateFolderToPrint(mainDoc, printerName, outputFolderCommon); Debug.WriteLine("Создана папка для печати: " + outputFolder); } //List<string> pfdFileNames = new List<string>(); //печатаю листы из каждого выбранного revit-файла List <MySheet> printedSheets = new List <MySheet>(); foreach (string docTitle in allSheets.Keys) { Document openedDoc = null; Debug.WriteLine("Печать листов из файла " + docTitle); RevitLinkType rlt = null; //проверяю, текущий это документ или полученный через ссылку if (docTitle == mainDocTitle) { openedDoc = mainDoc; Debug.WriteLine("Это не ссылочный документ"); } else { List <RevitLinkType> linkTypes = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkType)) .Cast <RevitLinkType>() .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Name) == docTitle) .ToList(); if (linkTypes.Count == 0) { throw new Exception("Cant find opened link file " + docTitle); } rlt = linkTypes.First(); //проверю, не открыт ли уже документ, который пытаемся печатать foreach (Document testOpenedDoc in commandData.Application.Application.Documents) { if (testOpenedDoc.IsLinked) { continue; } if (testOpenedDoc.Title == docTitle || testOpenedDoc.Title.StartsWith(docTitle) || docTitle.StartsWith(testOpenedDoc.Title)) { openedDoc = testOpenedDoc; Debug.WriteLine("Это открытый ссылочный документ"); } } //иначе придется открывать документ через ссылку if (openedDoc == null) { Debug.WriteLine("Это закрытый ссылочный документ, пытаюсь его открыть"); List <Document> linkDocs = new FilteredElementCollector(mainDoc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .Select(i => i.GetLinkDocument()) .Where(i => i != null) .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Title) == docTitle) .ToList(); if (linkDocs.Count == 0) { throw new Exception("Cant find link file " + docTitle); } Document linkDoc = linkDocs.First(); if (linkDoc.IsWorkshared) { Debug.WriteLine("Это файл совместной работы, открываю с отсоединением"); ModelPath mpath = linkDoc.GetWorksharingCentralModelPath(); OpenOptions oo = new OpenOptions(); oo.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; WorksetConfiguration wc = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets); oo.SetOpenWorksetsConfiguration(wc); rlt.Unload(new SaveCoordinates()); openedDoc = commandData.Application.Application.OpenDocumentFile(mpath, oo); } else { Debug.WriteLine("Это однопользательский файл"); string docPath = linkDoc.PathName; rlt.Unload(new SaveCoordinates()); openedDoc = commandData.Application.Application.OpenDocumentFile(docPath); } } Debug.WriteLine("Файл-ссылка успешно открыт"); } // List <MySheet> mSheets = allSheets[docTitle]; if (docTitle != mainDocTitle) { List <ViewSheet> linkSheets = new FilteredElementCollector(openedDoc) .OfClass(typeof(ViewSheet)) .Cast <ViewSheet>() .ToList(); List <MySheet> tempSheets = new List <MySheet>(); foreach (MySheet ms in mSheets) { foreach (ViewSheet vs in linkSheets) { if (ms.SheetId == vs.Id.IntegerValue) { MySheet newMs = new MySheet(vs, printSettings.alwaysColorParamName); tempSheets.Add(newMs); } } } mSheets = tempSheets; } Debug.WriteLine("Листов для печати найдено в данном файле: " + mSheets.Count.ToString()); Debug.WriteLine(": " + mSheets.Count.ToString()); PrintManager pManager = openedDoc.PrintManager; Debug.WriteLine("Текущий выбранный принтер: " + pManager.PrinterName); Debug.WriteLine("Попытка назначить принтер: " + printerName); pManager.SelectNewPrintDriver(printerName); pManager = openedDoc.PrintManager; pManager.PrintRange = PrintRange.Current; pManager.Apply(); Debug.WriteLine("Настройки менеджера печати успешно применены"); //список основных надписей нужен потому, что размеры листа хранятся в них //могут быть примечания, сделанные Основной надписью, надо их отфильровать, поэтому >0.6 List <FamilyInstance> titleBlocks = new FilteredElementCollector(openedDoc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_TitleBlocks) .Cast <FamilyInstance>() .Where(t => t.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble() > 0.6) .ToList(); Debug.WriteLine("Найдено основных надписей: " + titleBlocks.Count.ToString()); //получаю имя формата и проверяю, настроены ли размеры бумаги в Сервере печати string formatsCheckinMessage = PrintSupport.PrintFormatsCheckIn(openedDoc, printerName, titleBlocks, ref mSheets); if (formatsCheckinMessage != "") { message = formatsCheckinMessage; Debug.WriteLine("Проверка форматов листов неудачна: " + message); return(Result.Failed); } Debug.WriteLine("Проверка форматов листов выполнена успешно, переход к печати"); //если включен экспорт dwg - нахожу параметры экспорта по имени DWGExportOptions dwgOptions = null; if (printSettings.exportToDwg) { List <ExportDWGSettings> curDwgSettings = DwgSupport.GetAllDwgExportSettingsNames(openedDoc) .Where(i => i.Name == printSettings.selectedDwgExportProfileName) .ToList(); if (curDwgSettings.Count == 0) { TaskDialog.Show("Ошибка", "В файле " + openedDoc.Title + " не найден dwg профиль " + printSettings.selectedDwgExportProfileName); dwgOptions = DwgSupport.GetAllDwgExportSettingsNames(openedDoc).First().GetDWGExportOptions(); } else { dwgOptions = curDwgSettings.First().GetDWGExportOptions(); } } //печатаю каждый лист foreach (MySheet msheet in mSheets) { Debug.WriteLine(" "); Debug.WriteLine("Печатается лист: " + msheet.sheet.Name); if (printSettings.refreshSchedules) { SchedulesRefresh.Start(openedDoc, msheet.sheet); Debug.WriteLine("Спецификации обновлены успешно"); } using (Transaction t = new Transaction(openedDoc)) { t.Start("Профили печати"); string fileName0 = ""; if (printSettings.mergePdfs) { string guid = Guid.NewGuid().ToString(); fileName0 = msheet.sheet.SheetNumber + "_" + guid + ".pdf"; } else { fileName0 = msheet.NameByConstructor(printSettings.nameConstructor); } string fileName = SheetSupport.ClearIllegalCharacters(fileName0); if (fileName.Length > 128) { Debug.WriteLine("Имя листа длиннее 128 символов, будет урезано"); string cutname = fileName.Substring(0, 63); cutname += fileName.Substring(fileName.Length - 64); fileName = cutname; } if (printerName == "PDFCreator" && printSettings.useOrientation) { if (msheet.IsVertical) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Portrait); Debug.WriteLine("Принудительно установлена Portrait ориентация"); } if (!msheet.IsVertical) { SupportRegistry.SetOrientationForPdfCreator(OrientationType.Landscape); Debug.WriteLine("Принудительно установлена Landscape ориентация"); } } for (int i = 0; i < msheet.titleBlocks.Count; i++) { string tempFilename = ""; if (msheet.titleBlocks.Count > 1) { Debug.WriteLine("На листе более 1 основной надписи! Печать части №" + i.ToString()); tempFilename = fileName.Replace(".pdf", "_" + i.ToString() + ".pdf"); } else { Debug.WriteLine("На листе 1 основная надпись Id " + msheet.titleBlocks.First().Id.IntegerValue.ToString()); tempFilename = fileName; } string fullFilename = System.IO.Path.Combine(outputFolder, tempFilename); Debug.WriteLine("Полное имя файла: " + fullFilename); if (fullFilename.Length > 256) { throw new Exception("Слишком длинное имя файла " + fullFilename); } //смещаю область для печати многолистовых спецификаций double offsetX = -i * msheet.widthMm / 25.4; //смещение задается в дюймах! Debug.WriteLine("Смещение печати по X: " + offsetX.ToString("F3")); PrintSetting ps = PrintSupport.CreatePrintSetting(openedDoc, pManager, msheet, printSettings, offsetX, 0); pManager.PrintSetup.CurrentPrintSetting = ps; Debug.WriteLine("Настройки печати применены, " + ps.Name); PrintSupport.PrintView(msheet.sheet, pManager, ps, tempFilename); Debug.WriteLine("Лист успешно отправлен на принтер"); msheet.PdfFileName = fullFilename; printedSheets.Add(new MySheet(msheet)); } if (printerName == "PDFCreator" && printSettings.useOrientation) { System.Threading.Thread.Sleep(5000); } t.RollBack(); } //если включен dwg - то ещё экспортирую этот лист if (printSettings.exportToDwg) { List <ElementId> sheetsIds = new List <ElementId> { msheet.sheet.Id }; string sheetname = msheet.NameByConstructor(printSettings.dwgNameConstructor); openedDoc.Export(outputFolder, sheetname, sheetsIds, dwgOptions); } } if (rlt != null) { openedDoc.Close(false); #if R2017 RevitLinkLoadResult LoadResult = rlt.Reload(); #else LinkLoadResult loadResult = rlt.Reload(); #endif Debug.WriteLine("Ссылочный документ закрыт"); } } int printedSheetsCount = printedSheets.Count; printedSheets.Sort(); //если требуется постобработка файлов - ждем, пока они напечатаются if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs) { Debug.WriteLine("Включена постобработка файлов; ожидание окончания печати. Требуемое число файлов " + printedSheetsCount.ToString()); int watchTimer = 0; while (printToFile) { int filescount = System.IO.Directory.GetFiles(outputFolder, "*.pdf").Length; Debug.WriteLine("Итерация №" + watchTimer + ", файлов напечатано " + filescount); if (filescount >= printedSheetsCount) { break; } System.Threading.Thread.Sleep(500); watchTimer++; if (watchTimer > 100) { BalloonTip.Show("Обнаружены неполадки", "Печать PDF заняла продолжительное время или произошел сбой. Дождитесь окончания печати."); Debug.WriteLine("Не удалось дождаться окончания печати"); return(Result.Failed); } } } List <string> pdfFileNames = printedSheets.Select(i => i.PdfFileName).ToList(); Debug.WriteLine("PDF файлы которые должны быть напечатаны:"); foreach (string pdfname in pdfFileNames) { Debug.WriteLine(" " + pdfname); } Debug.WriteLine("PDF файлы напечатанные по факту:"); foreach (string pdfnameOut in System.IO.Directory.GetFiles(outputFolder, "*.pdf")) { Debug.WriteLine(" " + pdfnameOut); } //преобразую файл в черно-белый при необходимости if (printSettings.colorsType == ColorType.MonochromeWithExcludes) { Debug.WriteLine("Преобразование PDF файла в черно-белый"); foreach (MySheet msheet in printedSheets) { if (msheet.ForceColored) { Debug.WriteLine("Лист не преобразовывается в черно-белый: " + msheet.sheet.Name); continue; } string file = msheet.PdfFileName; string outFile = file.Replace(".pdf", "_OUT.pdf"); Debug.WriteLine("Файл будет преобразован из " + file + " в " + outFile); pdf.PdfWorker.SetExcludeColors(printSettings.excludeColors); pdf.PdfWorker.ConvertToGrayScale(file, outFile); //GrayscaleConvertTools.ConvertPdf(file, outFile, ColorType.Grayscale, new List<ExcludeRectangle> { rect, rect2 }); System.IO.File.Delete(file); System.IO.File.Move(outFile, file); Debug.WriteLine("Лист успешно преобразован"); } } //объединяю файлы при необходимости if (printSettings.mergePdfs) { Debug.WriteLine(" "); Debug.WriteLine("\nОбъединение PDF файлов"); System.Threading.Thread.Sleep(500); string combinedFile = System.IO.Path.Combine(outputFolder, mainDoc.Title + ".pdf"); BatchPrintYay.pdf.PdfWorker.CombineMultiplyPDFs(pdfFileNames, combinedFile); foreach (string file in pdfFileNames) { System.IO.File.Delete(file); Debug.WriteLine("Удален файл " + file); } Debug.WriteLine("Объединено успешно"); } if (printToFile) { System.Diagnostics.Process.Start(outputFolder); Debug.WriteLine("Открыта папка " + outputFolder); } //восстанавливаю настройки PDFCreator //if(printerName == "PDFCreator") //{ // SupportRegistry.RestoreSettingsForPDFCreator(); //} string msg = "Напечатано листов: " + printedSheetsCount; BalloonTip.Show("Печать завершена!", msg); Debug.WriteLine("Печать успешно завершена, напечатано листов " + printedSheetsCount); return(Result.Succeeded); }
public async void should_get_info_without_content() { var documentHandle = DocumentHandle.FromString("Pdf_2"); await _documentStoreClient.UploadAsync( TestConfig.PathToDocumentPdf, documentHandle ); // waits for storage await UpdateAndWaitAsync(); var format = new DocumentFormat("original"); var options = new OpenOptions() { FileName = "pluto.pdf", SkipContent = true }; var reader = _documentStoreClient.OpenRead(documentHandle, format, options); using (var downloaded = new MemoryStream()) { await (await reader.OpenStream()).CopyToAsync(downloaded); Assert.AreEqual(0, downloaded.Length); Assert.AreEqual(72768, reader.ContentLength); } }