Ejemplo n.º 1
0
        /// <summary>
        /// Печатает вид с заданными настройками печати.
        /// </summary>
        /// <param name="view"></param>
        /// <param name="pManager"></param>
        /// <param name="ps"></param>
        /// <param name="fileName"></param>
        public static void PrintView(View view, PrintManager pManager, PrintSetting ps, string fileName)
        {
            pManager.PrintSetup.CurrentPrintSetting = ps;

            fileName = @"C:\" + fileName;

            pManager.PrintToFileName = fileName;
            pManager.Apply();
            pManager.SubmitPrint(view);
            pManager.Apply();
        }
Ejemplo n.º 2
0
        private void PrintViewSheet(ViewSheet viewSheet, string sheetSize, PrintSetting printSetting, string filePath)
        {
            // creates view set
            ViewSet viewSet = new ViewSet();
            viewSet.Insert(viewSheet);
            PrintManager printManager = this.Doc.PrintManager;
            printManager.PrintRange = PrintRange.Select;
            printManager.Apply();

            // make new view set current
            ViewSheetSetting viewSheetSetting = printManager.ViewSheetSetting;
            viewSheetSetting.CurrentViewSheetSet.Views = viewSet;

            // set printer
            printManager.SelectNewPrintDriver(this._PrinterName);
            printManager.Apply();

            // set file path
            printManager.CombinedFile = true;
            printManager.PrintToFileName = filePath;
            printManager.Apply();

            // set print setting
            this.Transaction.Start();
            PrintSetup printSetup = printManager.PrintSetup;
            printSetup.CurrentPrintSetting = printSetting;
            printManager.Apply();
            this.Transaction.Commit();

            List<Element> viewSets = new List<Element>(new FilteredElementCollector(this.Doc)
                                                       .OfClass(typeof(ViewSheetSet))
                                                       .ToElements());
            foreach (Element element in viewSets)
            {
                if (element.Name == "tempSetName")
                {
                    this.Transaction.Start();
                    this.Doc.Delete(element.Id);
                    this.Transaction.Commit();
                }
            }

            // save settings and submit print
            this.Transaction.Start();
            viewSheetSetting.SaveAs("tempSetName");
            printManager.Apply();
            printManager.SubmitPrint();
            viewSheetSetting.Delete();
            this.Transaction.Commit();
        }
Ejemplo n.º 3
0
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public static bool PrintToDevice(
            Document doc,
            string size,
            PrintManager pm,
            string printerName,
            bool forceRaster,
            ExportLog log)
        {
            if (pm == null)
            {
                return(false);
            }

            PrintSetting ps = LoadRevitPrintSetting(doc, size, pm, printerName, forceRaster, log);

            if (ps == null)
            {
                return(false);
            }

            var t = new Transaction(doc, Resources.ApplyPrintSettings);

            t.Start();
            try {
                if (ps.IsValidObject)
                {
                    pm.PrintSetup.CurrentPrintSetting = ps;
                }
                else
                {
                    if (log != null)
                    {
                        log.AddWarning(null, Resources.WarningPrintSetupReadOnly);
                    }
                }
                pm.PrintRange = PrintRange.Current;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.PaperPlacement = PaperPlacementType.Margins;
                pm.PrintSetup.InSession.PrintParameters.PaperPlacement           = PaperPlacementType.Margins;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.MarginType     = MarginType.UserDefined;
                pm.PrintSetup.InSession.PrintParameters.MarginType = MarginType.UserDefined;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginX = 0;
                pm.PrintSetup.InSession.PrintParameters.UserDefinedMarginX           = 0;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginY = 0;
                pm.PrintSetup.InSession.PrintParameters.UserDefinedMarginY           = 0;
                pm.PrintToFile = false;
                pm.Apply();
                t.Commit();
                return(true);
            } catch (Exception ex) {
                System.Diagnostics.Debug.Print(ex.Message);
                if (log != null)
                {
                    log.AddError(null, ex.ToString());
                }
                t.RollBack();
                return(false);
            }
        }
Ejemplo n.º 4
0
        public string ChangePrintToFileName()
        {
            using (SaveFileDialog saveDlg = new SaveFileDialog()) {
                string postfix = null;

                switch (_printManager.IsVirtual)
                {
                case Autodesk.Revit.DB.VirtualPrinterType.AdobePDF:
                    saveDlg.Filter = "pdf files (*.pdf)|*.pdf";
                    postfix        = ".pdf";
                    break;

                case Autodesk.Revit.DB.VirtualPrinterType.DWFWriter:
                    saveDlg.Filter = "dwf files (*.dwf)|*.dwf";
                    postfix        = ".dwf";
                    break;

                case Autodesk.Revit.DB.VirtualPrinterType.None:
                    saveDlg.Filter = "prn files (*.prn)|*.prn";
                    postfix        = ".prn";
                    break;

                case VirtualPrinterType.XPSWriter:
                    saveDlg.Filter = "XPS files (*.xps)|*.xps";
                    postfix        = ".xps";
                    break;

                default:
                    break;
                }

                string title = _commandData.Application.ActiveUIDocument.Document.Title;
                if (title.Contains(".rvt"))
                {
                    saveDlg.FileName = title.Remove(title.LastIndexOf(".")) + postfix;
                }
                else
                {
                    saveDlg.FileName = title + postfix;
                }

                if (saveDlg.ShowDialog() == DialogResult.OK)
                {
                    _printManager.PrintToFileName = saveDlg.FileName;
                    _printManager.Apply();
                    return(_printManager.PrintToFileName);
                }
                else
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 5
0
        public static bool PrintToFile(
            Document doc,
            ExportSheet vs,
            PrintManager pm,
            string ext,
            string printerName)
        {
            if (pm == null || vs == null)
            {
                return(false);
            }
            if (vs.SCPrintSetting == null)
            {
                vs.UpdateSheetInfo();
                return(false);
            }

            if (!SetPrinterByName(doc, printerName, pm))
            {
                return(false);
            }

            using (var t = new Transaction(doc, "Print Pdf"))
            {
                if (t.Start() == TransactionStatus.Started)
                {
                    try {
                        if (!pm.PrintSetup.IsReadOnly)
                        {
                            pm.PrintSetup.CurrentPrintSetting = vs.SCPrintSetting;
                            pm.PrintRange      = PrintRange.Current;
                            pm.PrintToFile     = true;
                            pm.PrintToFileName = vs.FullExportPath(ext);
                            pm.Apply();
                            t.Commit();
                            return(true);
                        }
                        t.Commit();
                        return(false);
                    } catch (InvalidOperationException ex) {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        t.RollBack();
                        return(false);
                    }
                }
                else
                {
                    t.RollBack();
                    return(false);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // Filter all printable views in current document and print them,
            // the print will raise events registered in controlled application.
            // After run this external command please refer to log files under folder of this assembly.
            Document document = commandData.Application.ActiveUIDocument.Document;

            try
            {
                List <Autodesk.Revit.DB.Element> viewElems = new List <Autodesk.Revit.DB.Element>();
                FilteredElementCollector         collector = new FilteredElementCollector(document);
                viewElems.AddRange(collector.OfClass(typeof(View)).ToElements());
                //
                // Filter all printable views
                ViewSet printableViews = new ViewSet();
                foreach (View view in viewElems)
                {
                    // skip view templates because they're invalid for print
                    if (!view.IsTemplate && view.CanBePrinted)
                    {
                        printableViews.Insert(view);
                    }
                }
                //
                // Print to file to folder of assembly
                String       assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                PrintManager pm           = document.PrintManager;
                pm.PrintToFile     = true;
                pm.PrintToFileName = assemblyPath + "\\PrintOut.prn";
                pm.Apply();
                //
                // Print views now to raise events:
                document.Print(printableViews);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
            //
            // return succeed by default
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            Selection    selection = uidoc.Selection;
            PrintManager pm        = doc.PrintManager;

            pm.PrintRange = PrintRange.Select;
            ViewSheetSetting         vss = pm.ViewSheetSetting;
            ICollection <ElementId>  id;
            FilteredElementCollector collector;
            ElementClassFilter       wantedElements;
            PaperSizeSet             paperSize   = pm.PaperSizes;
            List <Element>           printElemes = null;


            using (Transaction trans = new Transaction(doc, "Print ViewSet"))
            {
                try
                {
                    id             = selection.GetElementIds();
                    collector      = new FilteredElementCollector(doc, id);
                    wantedElements = new ElementClassFilter(typeof(ViewSheet));
                    collector.WherePasses(wantedElements);
                    printElemes = collector.ToElements() as List <Element>;
                }
                catch (Autodesk.Revit.Exceptions.ApplicationException e)
                {
                    TaskDialog.Show("Error!", e.Message);
                    return(Result.Cancelled);
                }
                catch (Exception e)
                {
                    TaskDialog.Show("Error!", e.Message);
                }

                ViewSet viewSet = new ViewSet();

                foreach (var elem in printElemes)
                {
                    ViewSheet viewSheet = elem as ViewSheet;
                    viewSet.Insert(viewSheet);
                }

                trans.Start();

                try
                {
                    vss.CurrentViewSheetSet.Views = viewSet;
                    vss.Save();

                    pm.SelectNewPrintDriver("Microsoft Print to PDF");
                    pm.Apply();
                    //pm.PrintSetup.Save();

                    pm.PrintSetup.CurrentPrintSetting.PrintParameters.PageOrientation = PageOrientationType.Landscape;
                    pm.PrintSetup.CurrentPrintSetting.PrintParameters.PaperPlacement  = PaperPlacementType.Center;
                    pm.PrintSetup.CurrentPrintSetting.PrintParameters.ZoomType        = ZoomType.Zoom;
                    pm.PrintSetup.CurrentPrintSetting.PrintParameters.Zoom            = 100;
                    pm.CombinedFile = true;
                    //pm.PrintToFile = true;
                    //pm.PrintToFileName = @"C:\Users\Lenovo\Desktop\file.pdf";
                    pm.Apply();
                    //pm.PrintSetup.Save();
                    pm.SubmitPrint();
                }
                catch (Exception e)
                {
                    message = e.Message;
                    return(Result.Failed);
                }
                trans.Commit();
                // return Result.Succeeded;
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 9
0
        public static void print(Document doc)
        {
            ViewSet myViewSet = new ViewSet();
            var     collector =
                new FilteredElementCollector(doc)
                .OfClass(typeof(ViewSheet))
                .Cast <ViewSheet>().ToList();

            foreach (ViewSheet vs in collector)
            {
                if (!vs.IsTemplate && vs.CanBePrinted &&
                    vs.ViewType == ViewType.DrawingSheet)
                {
                    myViewSet.Insert(vs);
                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start("Transaction Name");
                        vs.Print(true);
                        tx.Commit();
                    }
                }
            }

            var printsettings = doc.GetPrintSettingIds();

            string       setName = Helper.RandomString(10);
            PrintManager pm      = doc.PrintManager;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Transaction Name");


                pm.SelectNewPrintDriver("Adobe PDF");

                //PaperSizeSet ps = pm.PaperSizes;
                pm.PrintRange   = PrintRange.Select;
                pm.CombinedFile = false;
                pm.PrintToFile  = true;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.RasterQuality   = RasterQualityType.Presentation;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.ColorDepth      = ColorDepthType.Color;
                pm.PrintSetup.CurrentPrintSetting.PrintParameters.ViewLinksinBlue = false;


                ViewSheetSetting viewSheetSetting = pm.ViewSheetSetting;

                // try
                // {
                // Save the current view sheet set to another view/sheet set with the specified name.
                viewSheetSetting.SaveAs(setName);
                //}
                //catch (Exception) { }
                viewSheetSetting.CurrentViewSheetSet.Views = myViewSet;
                viewSheetSetting.Save();
                pm.Apply();



                pm.PrintToFileName = FileManager.pdfout + setName + Convert.ToString(setName.GetHashCode()) + ".pdf";
                pm.SubmitPrint();
                tx.Commit();
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("print Name");
                pm.SubmitPrint();
                tx.Commit();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates print settings usable for the paper sizes of selected print set.
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            List <ViewSheet> viewSheetList = new List <ViewSheet>();

            if (selectedSheetSet == "Current sheet only")
            {
                Autodesk.Revit.DB.View view = doc.ActiveView;
                viewSheetList.Add((ViewSheet)view);
            }
            else
            {
                FilteredElementCollector col = new FilteredElementCollector(doc);
                var sheetSet = col.OfClass(typeof(ViewSheetSet))
                               .Where(x => x.Name == selectedSheetSet)
                               .Cast <ViewSheetSet>().FirstOrDefault();
                foreach (ViewSheet vs in sheetSet.Views)
                {
                    viewSheetList.Add(vs);
                }
            }

            PrintManager pm = doc.PrintManager;
            PrintSetup   ps = pm.PrintSetup;

            pm.SelectNewPrintDriver("Bluebeam PDF");
            pm = doc.PrintManager;
            ps = pm.PrintSetup;
            var paperSizes = pm.PaperSizes;

            FilteredElementCollector colPs = new FilteredElementCollector(doc);
            var printSettings = colPs.OfClass(typeof(PrintSetting)).Cast <PrintSetting>().ToHashSet();

            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("PrintSettings");
                //PrintManager pm = doc.PrintManager;

                foreach (ViewSheet sheet in viewSheetList)
                {
                    FamilyInstance titleBlock =
                        fi.GetElements <FamilyInstance, BuiltInParameter>(doc, BuiltInParameter.SHEET_NUMBER, sheet.SheetNumber).FirstOrDefault();

                    var widthPar = titleBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH);
                    var width    = Convert.ToInt32(widthPar.AsDouble().FtToMm().Round(0));

                    var heightPar = titleBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT);
                    var height    = Convert.ToInt32(heightPar.AsDouble().FtToMm().Round(0));

                    var nameOfPaperSize = paperSizeDict[height][width];

                    if (printSettings.Any(x => x.Name == nameOfPaperSize))
                    {
                        PrintSetting pset = printSettings.Where(x => x.Name == nameOfPaperSize).FirstOrDefault();
                        printSettings = printSettings.ExceptWhere(x => x.Name == nameOfPaperSize).ToHashSet();
                        doc.Delete(pset.Id);
                        doc.Regenerate();
                    }

                    pm.PrintRange  = PrintRange.Select;
                    pm.PrintToFile = true;

                    PrintSetup pSetup = pm.PrintSetup;
                    pSetup.CurrentPrintSetting = pm.PrintSetup.InSession;
                    PrintParameters pParams = pSetup.CurrentPrintSetting.PrintParameters;

                    pParams.ZoomType        = ZoomType.Zoom;
                    pParams.Zoom            = 100;
                    pParams.PageOrientation = PageOrientationType.Landscape;
                    pParams.PaperPlacement  = PaperPlacementType.Center;
                    if (radioButton1.Checked)
                    {
                        pParams.ColorDepth = ColorDepthType.Color;
                    }
                    else if (radioButton2.Checked)
                    {
                        pParams.ColorDepth = ColorDepthType.GrayScale;
                    }
                    else if (radioButton3.Checked)
                    {
                        pParams.ColorDepth = ColorDepthType.BlackLine;
                    }
                    pParams.RasterQuality                = RasterQualityType.Presentation;
                    pParams.HiddenLineViews              = HiddenLineViewsType.VectorProcessing;
                    pParams.ViewLinksinBlue              = false;
                    pParams.HideReforWorkPlanes          = true;
                    pParams.HideUnreferencedViewTags     = true;
                    pParams.HideCropBoundaries           = true;
                    pParams.HideScopeBoxes               = true;
                    pParams.ReplaceHalftoneWithThinLines = false;
                    pParams.MaskCoincidentLines          = false;

                    var paperSize = (from PaperSize psize in paperSizes where psize.Name.Equals(nameOfPaperSize) select psize).FirstOrDefault();

                    pParams.PaperSize = paperSize ?? throw new Exception("Printer does not have specified paper size! Check paper size configuration.");

                    pm.Apply();

                    try
                    {
                        pm.PrintSetup.SaveAs(paperSize.Name);
                    }
                    catch (Exception)
                    {
                    }
                }

                trans.Commit();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Retrieves print setting created for the specific paper size and prints all sheets in the set.
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            //string sheetFileName;
            //string fullSheetFileName;
            //IList<string> fileNamesSource = new List<string>();
            //IList<string> fileNamesDefault = new List<string>();

            //Clear the fileNamesDestination
            fileNames.Clear();

            using (Transaction trans = new Transaction(doc))
            {
                //Update status window
                textBox8.Text = "Preparing print";

                trans.Start("Print!");

                List <ViewSheet> viewSheetList = new List <ViewSheet>();

                if (selectedSheetSet == "Current sheet only")
                {
                    Autodesk.Revit.DB.View view = doc.ActiveView;
                    viewSheetList.Add((ViewSheet)view);
                }
                else
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc);
                    var sheetSet = col.OfClass(typeof(ViewSheetSet))
                                   .Where(x => x.Name == selectedSheetSet)
                                   .Cast <ViewSheetSet>().FirstOrDefault();
                    foreach (ViewSheet vs in sheetSet.Views)
                    {
                        viewSheetList.Add(vs);
                    }
                }

                FilteredElementCollector colPs = new FilteredElementCollector(doc);
                var printSettings = colPs.OfClass(typeof(PrintSetting)).Cast <PrintSetting>().ToHashSet();

                PrintManager pm = doc.PrintManager;
                PrintSetup   ps = pm.PrintSetup;
                pm.SelectNewPrintDriver("Bluebeam PDF");
                pm = doc.PrintManager;
                ps = pm.PrintSetup;
                var paperSizes = pm.PaperSizes;

                string title = doc.Title; //<- THIS CAN CAUSE PROBLEMS RECOGNISING THE ORIGINAL FILE NAME

                int sheetCount = 0;

                foreach (ViewSheet sheet in viewSheetList)
                {
                    #region Naming
                    //var revisionType = sheet.GetCurrentRevision();

                    FileNames fileName = new FileNames();
                    fileNames.Add(fileName);

                    Parameter sheetNumberPar = sheet.get_Parameter(BuiltInParameter.SHEET_NUMBER);
                    string    sheetNumber    = sheetNumberPar.AsString();
                    fileName.SheetNumber = sheetNumber;

                    Parameter sheetNamePar = sheet.get_Parameter(BuiltInParameter.SHEET_NAME);
                    string    sheetName    = sheetNamePar.AsString();
                    fileName.SheetName = sheetName;

                    Parameter curRevisionPar = sheet.get_Parameter(BuiltInParameter.SHEET_CURRENT_REVISION);
                    string    revision       = curRevisionPar.AsString();
                    fileName.Revision = revision;

                    Parameter curRevisionDatePar = sheet.get_Parameter(BuiltInParameter.SHEET_CURRENT_REVISION_DATE);
                    string    revisionDate       = curRevisionDatePar.AsString();
                    fileName.RevisionDate = revisionDate;

                    Parameter sheetIssueDatePar = sheet.get_Parameter(BuiltInParameter.SHEET_ISSUE_DATE);
                    string    sheetIssueDate    = sheetIssueDatePar.AsString();
                    fileName.Date = sheetIssueDate;

                    Parameter curScalePar = sheet.LookupParameter("Scale");
                    if (curScalePar != null)
                    {
                        if (curScalePar.AsString() == "As indicated")
                        {
                            Parameter curScaleManualPar = sheet.LookupParameter("Manual skala");
                            if (curScaleManualPar != null)
                            {
                                fileName.Scale = curScaleManualPar.AsString();
                            }
                        }
                        else if (curScalePar.AsString() != "As indicated")
                        {
                            fileName.Scale = curScalePar.AsString();
                        }
                    }

                    Parameter sorting1Par = sheet.LookupParameter("RDK-COM-SHT-SORTING_1");
                    string    sorting1    = sorting1Par.AsString();
                    Parameter sorting2Par = sheet.LookupParameter("RDK-COM-SHT-SORTING_2");
                    string    sorting2    = sorting2Par.AsString();
                    fileName.DrawingListCategory = sorting1 + " - " + sorting2;

                    fileName.GenerateFileName();

                    fileName.FileNameWithPath = pathToExport + fileName.FileName;                                                       //Used to copy files later

                    string printfilename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + fileName.FileName; //Used to satisfy bluebeam
                    //fileNamesSource.Add(printfilename);

                    //string defaultFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                    //    + "\\" + title + " - Sheet - " + sheet.SheetNumber + " - " + sheet.Name + ".pdf";
                    //fileNamesDefault.Add(defaultFileName);

                    pm.PrintToFileName = printfilename;
                    #endregion

                    FamilyInstance titleBlock =
                        fi.GetElements <FamilyInstance, BuiltInParameter>(doc, BuiltInParameter.SHEET_NUMBER, sheet.SheetNumber).FirstOrDefault();

                    var widthPar = titleBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH);
                    var width    = Convert.ToInt32(widthPar.AsDouble().FtToMm().Round(0));

                    var heightPar = titleBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT);
                    var height    = Convert.ToInt32(heightPar.AsDouble().FtToMm().Round(0));

                    var nameOfPaperSize = paperSizeDict[height][width];

                    var printSetting = (from PrintSetting pSetting in printSettings
                                        where pSetting.Name == nameOfPaperSize
                                        select pSetting).FirstOrDefault();

                    ps.CurrentPrintSetting = printSetting ?? throw new Exception($"{sheet.Name} does not have a print setting!");

                    pm.Apply();

                    //Feedback
                    sheetCount++;
                    textBox8.Text = "Sending " + sheetCount;

                    pm.SubmitPrint(sheet);

                    //Also export to DWF
                    DWFExportOptions dwfOptions    = new DWFExportOptions();
                    string           dwfExportPath = pathToExport + "\\DWF";
                    System.IO.Directory.CreateDirectory(dwfExportPath);

                    ViewSet vs = new ViewSet();
                    vs.Insert(sheet);

                    doc.Export(dwfExportPath, fileName.FileName.Remove(fileName.FileName.Length - 4), vs, dwfOptions);

                    System.Threading.Thread.Sleep(3000);
                }



                trans.Commit();
            }
            ////File handling
            //if (WaitForFile(fileNamesSource.Last(), fileNamesDefault.Last()))
            //{
            //    var result = tryOpenFiles(fileNamesSource.Last(), fileNamesDefault.Last());

            //    if (result.Item1)
            //    {
            //        foreach (var files in fileNamesSource.Zip(fileNamesDestination, Tuple.Create))
            //        {
            //            if (File.Exists(files.Item2)) File.Delete(files.Item2);
            //            File.Move(files.Item1, files.Item2);
            //        }
            //    }
            //    else if (result.Item2)
            //    {
            //        foreach (var files in fileNamesDefault.Zip(fileNamesDestination, Tuple.Create))
            //        {
            //            if (File.Exists(files.Item2)) File.Delete(files.Item2);
            //            File.Move(files.Item1, files.Item2);
            //        }
            //    }
            //    else throw new Exception("Filename handling FAILED AGAIN!!!!!!!");

            //}
            //else Shared.BuildingCoder.BuildingCoderUtilities.ErrorMsg("The copying of files failed for some reason!");
        }