Esempio n. 1
0
        public virtual void SaveAs()
        {
            var dwgtitled = Application.GetSystemVariable("DWGTITLED");

            if (Convert.ToInt16(dwgtitled) == 0)
            {
                throw new Exception("图纸为临时图纸,不能保存");
            }
            var ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            var db_source = HostApplicationServices.WorkingDatabase;
            var dir       = new FileInfo(db_source.OriginalFileName).Directory;

            dir = new DirectoryInfo($@"{dir.FullName}\support");
            dir.Create();
            var op_file = new PromptSaveFileOptions("选择目标文件" + Environment.NewLine);

            op_file.InitialDirectory = $@"{dir.FullName}";
            op_file.Filter           = "图形配置文件-json格式 (*.enf)|*.enf";
            var result_file = ed.GetFileNameForSave(op_file);

            if (result_file.Status == PromptStatus.OK)
            {
                File.WriteAllText(result_file.StringResult, JsonConvert.SerializeObject(this));
            }
        }
Esempio n. 2
0
        Stream(ArrayList data, PromptFileOptions promptFileOpts)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(PromptFileOptions)));

            data.Add(new Snoop.Data.Bool("AllowUrls", promptFileOpts.AllowUrls));
            data.Add(new Snoop.Data.String("Dialog caption", promptFileOpts.DialogCaption));
            data.Add(new Snoop.Data.String("Dialog name", promptFileOpts.DialogName));
            data.Add(new Snoop.Data.String("Filter", promptFileOpts.Filter));
            data.Add(new Snoop.Data.Int("Filter index", promptFileOpts.FilterIndex));
            data.Add(new Snoop.Data.String("Initial directory", promptFileOpts.InitialDirectory));
            data.Add(new Snoop.Data.String("Initial file name", promptFileOpts.InitialFileName));
            data.Add(new Snoop.Data.String("Message", promptFileOpts.Message));
            data.Add(new Snoop.Data.Bool("Prefer command line", promptFileOpts.PreferCommandLine));

            PromptOpenFileOptions promptOpenFileOpts = promptFileOpts as PromptOpenFileOptions;

            if (promptOpenFileOpts != null)
            {
                Stream(data, promptOpenFileOpts);
                return;
            }

            PromptSaveFileOptions promptSaveFileOpts = promptFileOpts as PromptSaveFileOptions;

            if (promptSaveFileOpts != null)
            {
                Stream(data, promptSaveFileOpts);
                return;
            }
        }
Esempio n. 3
0
        Stream(ArrayList data, PromptSaveFileOptions promptSaveFileOpts)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(PromptSaveFileOptions)));

            data.Add(new Snoop.Data.Bool("Derive initial filename from drawing name", promptSaveFileOpts.DeriveInitialFilenameFromDrawingName));
            data.Add(new Snoop.Data.Bool("Display save options menu item", promptSaveFileOpts.DisplaySaveOptionsMenuItem));
            data.Add(new Snoop.Data.Bool("Force overwrite warning for scripts and lisp", promptSaveFileOpts.ForceOverwriteWarningForScriptsAndLisp));
        }
Esempio n. 4
0
        internal static string SelectFolder(string promptText)
        {
            //ask for a file using the open file dialog
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptSaveFileOptions op = new PromptSaveFileOptions(promptText);

            op.InitialDirectory = "C:\\";
            op.Filter           = "CSV Files (*.csv)|*.csv";
            op.FilterIndex      = 2;
            PromptFileNameResult fn = ed.GetFileNameForSave(op);

            return(fn.StringResult);
        }
        public void CreateAndSaveDwg()
        {
            //新建一个数据库对象以创建新的Dwg文件
            Database db = new Database();

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //获取数据库的块表对象
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                //获取数据库的模型空间块表记录对象
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                //新建两个圆
                Circle cir1 = new Circle(new Point3d(1, 1, 0), Vector3d.ZAxis, 1.0);
                Circle cir2 = new Circle(new Point3d(4, 4, 0), Vector3d.ZAxis, 2.0);
                //在模型空间中加入新建的两个圆
                btr.AppendEntity(cir1);
                trans.AddNewlyCreatedDBObject(cir1, true);
                btr.AppendEntity(cir2);
                trans.AddNewlyCreatedDBObject(cir2, true);

                //定义保存文件对话框
                PromptSaveFileOptions opt = new PromptSaveFileOptions("\n请输入文件名:");
                //保存文件对话框的文件扩展名列表
                opt.Filter = "图形(*.dwg)|*.dwg|图形(*.dxf)|*.dxf";
                //文件过滤器列表中缺省显示的文件扩展名
                opt.FilterIndex = 0;
                //保存文件对话框的标题
                opt.DialogCaption = "图形另存为";
                //缺省保存目录
                opt.InitialDirectory = "C:\\";
                //缺省保存文件名(扩展名由扩展名列表中的当前值确定)
                opt.InitialFileName = "MyDwg";
                //获取当前数据库对象(不是上面新建的)的命令行对象
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                //根据保存对话框中用户的选择,获取保存文件名
                string filename = ed.GetFileNameForSave(opt).StringResult;
                //保存文件为当前AutoCAD版本
                db.SaveAs(filename, DwgVersion.Current);
            }
        }
Esempio n. 6
0
        private void promptUserExportFile()
        {
            // Запрос имени экспортированного файла у пользователя
            Editor ed    = _docAkr.Editor;
            var    prOpt = new PromptSaveFileOptions("Имя экспортируемого файла");

            prOpt.InitialFileName  = FileExportFacade.Name;
            prOpt.InitialDirectory = FileExportFacade.DirectoryName;
            //prOpt.DialogCaption = "";
            prOpt.DialogName = "Экспорт";
            prOpt.Message    = "Новый файл или существующий - в существующем файле заменятся блоки панелей.";
            prOpt.Filter     = "Чертеж |*.dwg";
            var res = ed.GetFileNameForSave(prOpt);

            if (res.Status != PromptStatus.OK)
            {
                throw new Exception("Отменено пользователем.");
            }
            FileExportFacade   = new FileInfo(getDwgFileName(res.StringResult));
            IsExistsFileExport = FileExportFacade.Exists;
            // Если файл существует, то спросить подтверждение экспорта фасадов в существующий файл.
            // Не нужно, т.к. в диалоге уже выдается такой вопрос.
            //if (IsExistsFileExport)
            //{
            //   var messageRes = MessageBox.Show("Такой файл уже существует. Выполнить повторный экспорт фасада в этот файл? \n" +
            //      "Старые панели в файле будут заменены на новые.", "Повторный экспорт",
            //      MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Yes);
            //   if (messageRes == MessageBoxResult.No)
            //   {
            //      // Повтор запроса имени файла
            //      promptUserExportFile();
            //   }
            //   else if (messageRes == MessageBoxResult.Cancel)
            //   {
            //      throw new Exception("Отменено пользователем.");
            //   }
            //}
        }
Esempio n. 7
0
        public static string GetFilename(
            this Editor ed, string prompt, bool openFile = true
            )
        {
            PromptFileNameResult pfnr;

            if (openFile)
            {
                var pofo = new PromptOpenFileOptions(prompt);
                pfnr = ed.GetFileNameForOpen(pofo);
            }
            else
            {
                var psfo = new PromptSaveFileOptions(prompt);
                pfnr = ed.GetFileNameForSave(psfo);
            }

            if (pfnr.Status != PromptStatus.OK)
            {
                return(null);
            }

            return(pfnr.StringResult);
        }
Esempio n. 8
0
 private void promptUserExportFile()
 {
     // Запрос имени экспортированного файла у пользователя
      Editor ed = _docAkr.Editor;
      var prOpt = new PromptSaveFileOptions("Имя экспортируемого файла");
      prOpt.InitialFileName = FileExportFacade.Name;
      prOpt.InitialDirectory = FileExportFacade.DirectoryName;
      //prOpt.DialogCaption = "";
      prOpt.DialogName = "Экспорт";
      prOpt.Message = "Новый файл или существующий - в существующем файле заменятся блоки панелей.";
      prOpt.Filter = "Чертеж |*.dwg";
      var res = ed.GetFileNameForSave(prOpt);
      if (res.Status != PromptStatus.OK)
      {
     throw new Exception("Отменено пользователем.");
      }
      FileExportFacade = new FileInfo(getDwgFileName(res.StringResult));
      IsExistsFileExport = FileExportFacade.Exists;
      // Если файл существует, то спросить подтверждение экспорта фасадов в существующий файл.
      // Не нужно, т.к. в диалоге уже выдается такой вопрос.
      //if (IsExistsFileExport)
      //{
      //   var messageRes = MessageBox.Show("Такой файл уже существует. Выполнить повторный экспорт фасада в этот файл? \n" +
      //      "Старые панели в файле будут заменены на новые.", "Повторный экспорт",
      //      MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Yes);
      //   if (messageRes == MessageBoxResult.No)
      //   {
      //      // Повтор запроса имени файла
      //      promptUserExportFile();
      //   }
      //   else if (messageRes == MessageBoxResult.Cancel)
      //   {
      //      throw new Exception("Отменено пользователем.");
      //   }
      //}
 }
Esempio n. 9
0
        public override void SaveAs()
        {
            var dwgtitled = Application.GetSystemVariable("DWGTITLED");

            if (Convert.ToInt16(dwgtitled) == 0)
            {
                throw new Exception("图纸为临时图纸,不能保存");
            }

            var ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            var db_source = HostApplicationServices.WorkingDatabase;
            var dir       = new FileInfo(db_source.OriginalFileName).Directory;

            dir = new DirectoryInfo($@"{dir.FullName}\support");
            dir.Create();
            var op_file = new PromptSaveFileOptions("选择目标文件" + Environment.NewLine);

            op_file.InitialDirectory = $@"{dir.FullName}";

            op_file.InitialFileName = $"{BlockName}.enf";
            op_file.Filter          = "图形配置文件-json格式 (*.enf)|*.enf";

            var result_file = ed.GetFileNameForSave(op_file);

            if (result_file.Status == PromptStatus.OK)
            {
                if (BlockName != null)
                {
                    var file = new FileInfo(result_file.StringResult.Replace(".enf", "_block.dwg"));
                    var doc  = Application.DocumentManager.MdiActiveDocument;
                    using (doc.LockDocument())
                    {
                        var selection = ed.SelectImplied();
                        var ids       = selection.Value.GetObjectIds();
                        using (var tr_source = db_source.TransactionManager.StartTransaction())
                        {
                            var br  = tr_source.GetObject(selection.Value[0].ObjectId, OpenMode.ForRead) as BlockReference;
                            var mtx = Matrix3d.Displacement(Point3d.Origin - br.Position);

                            var       targetObjectIds = new ObjectIdCollection(ids);
                            IdMapping mapping         = new IdMapping();
                            using (var db_target = new Database(true, true))
                            {
                                using (var tr_target = db_target.TransactionManager.StartTransaction())
                                {
                                    var targetid = ((BlockTable)tr_target.GetObject(db_target.BlockTableId, OpenMode.ForRead))[BlockTableRecord.ModelSpace];
                                    db_source.WblockCloneObjects(targetObjectIds, targetid, mapping, DuplicateRecordCloning.Replace, false);

                                    var btr = tr_target.GetObject(targetid, OpenMode.ForRead) as BlockTableRecord;
                                    foreach (var oid in btr)
                                    {
                                        var ent = tr_target.GetObject(oid, OpenMode.ForWrite) as Entity;
                                        if (ent != null)
                                        {
                                            ent.TransformBy(mtx);
                                        }
                                    }

                                    tr_target.Commit();
                                }
                                if (file.FullName.ToLower().EndsWith("dxf"))
                                {
                                    db_target.DxfOut(file.FullName, 16, DwgVersion.Current);
                                }
                                else
                                {
                                    db_target.SaveAs(file.FullName, DwgVersion.Current);
                                }
                            }
                            tr_source.Abort();
                        }
                    }
                }
                File.WriteAllText(result_file.StringResult, JsonConvert.SerializeObject(this));
            }
        }
Esempio n. 10
0
        public void fgetpoints()
        {
            try
            {
                Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
                Database acCurDb = acDoc.Database;
                Editor   ed      = acDoc.Editor;

                Utils.Utils.Init();

                PromptSelectionOptions peo = new PromptSelectionOptions();
                //PromptEntityOptions peo = new PromptEntityOptions("\nSelect mesh:");
                peo.AllowDuplicates = false;
                PromptSelectionResult per = ed.GetSelection(peo);
                if (per.Status != PromptStatus.OK || per.Status == PromptStatus.Cancel || per.Status == PromptStatus.Error || per.Status == PromptStatus.None)
                {
                    Utils.Utils.End();
                    return;
                }

                // Enter file name
                string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var    psfo      = new PromptSaveFileOptions("Export complex geometry");
                psfo.Filter = "txt (*.txt)|*.txt";
                var pr = ed.GetFileNameForSave(psfo);

                if (pr.Status != PromptStatus.OK)
                {
                    return;
                }

                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    using (StreamWriter outputFile = new StreamWriter(pr.StringResult))
                    {
                        SelectionSet acSSet = per.Value;

                        // Step through the objects in the selection set
                        foreach (SelectedObject acSSObj in acSSet)
                        {
                            Entity entity = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;
                            if (entity.GetType() == typeof(SubDMesh))
                            {
                                SubDMesh mesh = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as SubDMesh;
                                if (mesh != null)
                                {
                                    // Generate array that contains info about faces, i.e. [0] => number of edges, [1] => vert[0], [2] => vert[1], ...
                                    int[]             faceArr  = mesh.FaceArray.ToArray();
                                    Point3dCollection vertices = mesh.Vertices;
                                    int edges = 0;

                                    // Append text to selected file named.
                                    outputFile.WriteLine("&GEOM ID='COMPLEX_GEOM_1',");
                                    outputFile.WriteLine("SURF_ID = '" + Utils.Layers.GetSurfaceName(mesh.Layer.ToString()) + "',");
                                    outputFile.Write("VERTS =\t");
                                    foreach (Point3d vertice in vertices)
                                    {
                                        if (vertice == vertices[0])
                                        {
                                            outputFile.Write(String.Format("{0}, {1}, {2},\n", vertice.X, vertice.Y, vertice.Z));
                                        }
                                        else
                                        {
                                            outputFile.Write(String.Format("\t\t{0}, {1}, {2},\n", vertice.X, vertice.Y, vertice.Z));
                                        }
                                    }

                                    outputFile.Write(String.Format("FACES =\t"));
                                    // x = edges
                                    // x + 1 = vertice 1
                                    // x + 2 = vertice 2
                                    // x + 3 = vertice 3
                                    for (int x = 0; x < faceArr.Length; x = x + edges + 1) // Zacznij od 0; mniejsze od dlugosci; zrob skok co 3 (liczba krawedzi) + 1
                                    {
                                        if (x == 0)
                                        {
                                            outputFile.Write(String.Format("{0}, {1}, {2}, 1,\n", faceArr[x + 1] + 1, faceArr[x + 2] + 1, faceArr[x + 3] + 1));
                                        }
                                        else
                                        {
                                            outputFile.Write(String.Format("\t\t{0}, {1}, {2}, 1,\n", faceArr[x + 1] + 1, faceArr[x + 2] + 1, faceArr[x + 3] + 1));
                                        }

                                        edges = faceArr[x]; // face array na x posiada info ile jest krawedzi - dla nas zawsze 3
                                    }
                                    outputFile.WriteLine("/\n\n");
                                }
                            }
                        }
                    }
                    acTrans.Commit();
                }
                Utils.Utils.End();
                return;
            }
            catch (System.Exception e)
            {
                Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;
                ed.WriteMessage("Program error: " + e.ToString());
                Utils.Utils.End();
                return;
            }
        }
Esempio n. 11
0
        public void PrintTT()
        {
            Document      acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb   = acDoc.Database;
            Editor        ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            List <String> imagelist = new List <String>();

            string directory = @"D:\";//磁盘路径
            string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels");

            try
            {
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        int flag = 0;
                        //获取当前布局管理器变量
                        LayoutManager acLayoutMgr = LayoutManager.Current;
                        //获取当前布局变量
                        Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead);
                        //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite);
                        //获取当前布局的打印信息
                        PlotInfo acPlInfo = new PlotInfo()
                        {
                            Layout = acLayout.ObjectId
                        };



                        //提示用户输入打印窗口的两个角点
                        PromptPointResult resultp = ed.GetPoint("\n指定第一个角点");
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d basePt = resultp.Value;
                        resultp = ed.GetCorner("指定对角点", basePt);
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d cornerPt = resultp.Value;

                        //选择实体对象
                        // PromptSelectionOptions result1 = new PromptSelectionOptions();

                        SelectionFilter frameFilter = new SelectionFilter(
                            new TypedValue[]
                            { new TypedValue(0, "LWPOLYLINE"),
                              new TypedValue(90, 4),
                              new TypedValue(70, 1) });


                        PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter);
                        // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter);
                        PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter);
                        if (selectedFrameResult.Status == PromptStatus.OK)
                        {
                            List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            List <ObjectId> resultObjectIds   = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds);
                            foreach (ObjectId frameId in resultObjectIds)
                            {
                                Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline;
                                framePline.Highlight();
                            }


                            PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                            acPlSet.CopyFrom(acLayout);
                            //着色打印选项,设置按线框进行打印
                            acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe;
                            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                            //打印比例
                            //用户标准打印
                            acPlSetVdr.SetUseStandardScale(acPlSet, true);
                            acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                            //居中打印
                            acPlSetVdr.SetPlotCentered(acPlSet, true);
                            //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet
                            System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList();
                            //设置打印样式表
                            if (comboBoxStyleSheet.SelectedItem.ToString() == "无")
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb");
                            }

                            else
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString());
                            }

                            //选择方向
                            if (radioButtonHorizontal.Checked)
                            {
                                //横向
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                            }

                            //竖向
                            if (radioButtonVertical.Checked)
                            {
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                            }
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true);
                            string             imagename   = "";
                            string[]           files       = new string[] { };
                            List <string>      listfile    = new List <string>();
                            foreach (var frame in resultObjectIds)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }
                                flag++;

                                Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity;

                                imagename = string.Format("{0}-{1}.pdf", frame, flag);
                                //imagelist.Add(directory + imagename);
                                listfile.Add(directory + imagename);


                                //设置是否使用打印样式
                                acPlSet.ShowPlotStyles = true;
                                //设置打印区域
                                Extents3d extents3d = ent.GeometricExtents;

                                Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y);
                                acPlSetVdr.SetPlotWindowArea(acPlSet, E2d);
                                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                //重载和保存打印信息
                                acPlInfo.OverrideSettings = acPlSet;
                                //验证打印信息设置,看是否有误
                                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                acPlInfoVdr.Validate(acPlInfo);

                                while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                                {
                                    continue;
                                }
                                #region BackUpCode

                                //保存App的原参数
                                short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                                //设定为前台打印,加快打印速度
                                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                                PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine();
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                                //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                acPlEng1.BeginPlot(acPlProgDlg, null);
                                acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                                //  acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng1.BeginGenerateGraphics(null);
                                acPlEng1.EndGenerateGraphics(null);
                                acPlEng1.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                acPlEng1.EndDocument(null);
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng1.EndPlot(null);
                                acPlEng1.Dispose();
                                acPlEng1.Destroy();
                                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);

                                #endregion
                            }


                            files = listfile.ToArray();
                            PlotConfig config = PlotConfigManager.CurrentConfig;
                            //获取去除扩展名后的文件名(不含路径)
                            string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg");
                            //定义保存文件对话框
                            PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名")
                            {
                                //保存文件对话框的文件扩展名列表
                                Filter           = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension,
                                DialogCaption    = "浏览打印文件",                            //保存文件对话框的标题
                                InitialDirectory = @"D:\",                              //缺省保存目录
                                InitialFileName  = fileName + "-" + acLayout.LayoutName //缺省保存文件名
                            };
                            //根据保存对话框中用户的选择,获取保存文件名
                            PromptFileNameResult result = ed.GetFileNameForSave(opt);
                            if (result.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            fileName = result.StringResult;

                            //string fileName = @"D:\输出.pdf";
                            PdfDocumentBase docx = PdfDocument.MergeFiles(files);
                            docx.Save(fileName, FileFormat.PDF);
                            System.Diagnostics.Process.Start(fileName);



                            //保存App的原参数
                            short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                            //设定为前台打印,加快打印速度
                            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                            PlotEngine acPlEng = PlotFactory.CreatePublishEngine();
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;
                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;
                            PlotPageInfo acPlPageInfo1 = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null);
                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();
                            acPlEng.EndDocument(null);
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                            acPlEng.Dispose();
                            acPlEng.Destroy();
                            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1);

                            acPlProgDlg.Dispose();
                            acPlProgDlg.Destroy();

                            for (int i = 0; i < files.Length; i++)
                            {
                                File.Delete(files[i]);
                            }
                        }
                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            continue;
                        }
                        //MessageBox.Show("打印完成!");
                    }
                }
                else
                {
                    ed.WriteMessage("\n另一个打印进程正在进行中.");
                }
            }



            catch (System.Exception)
            {
                throw;
            }
        }
Esempio n. 12
0
        [CommandMethod("expsurfpts")] //Comanda pentru exportarea intr-un fisier PENZD.csv a punctelor unei suprafete
        public void ExpSurfPts()
        {
            CivilDocument      civDoc  = CivilApplication.ActiveDocument;
            Document           acadDoc = Application.DocumentManager.MdiActiveDocument;
            Database           db      = HostApplicationServices.WorkingDatabase;
            Editor             ed      = acadDoc.Editor;
            ObjectIdCollection surfIds = civDoc.GetSurfaceIds();

            //Verificarea existentei a cel putin unei suprafete
            if (surfIds.Count == 0)
            {
                ed.WriteMessage("\nNo Surfaces found!");
                return;
            }

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //Selectarea suprafetei
                Autodesk.Civil.DatabaseServices.Surface suprafata;
                if (surfIds.Count == 1)
                {
                    suprafata = (Autodesk.Civil.DatabaseServices.Surface)trans.GetObject(surfIds[0], OpenMode.ForRead);
                }
                else
                {
                    PromptEntityOptions PrEntOpt = new PromptEntityOptions("\nSelect Surface: ");
                    PrEntOpt.AllowNone = false;
                    PrEntOpt.SetRejectMessage("\nSelected object is not a Civil3D surface!");
                    PrEntOpt.AddAllowedClass(typeof(Autodesk.Civil.DatabaseServices.Surface), false);
                    PromptEntityResult PrEntRes = ed.GetEntity(PrEntOpt);
                    if (PrEntRes.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\nAborting!");
                        return;
                    }
                    suprafata = (Autodesk.Civil.DatabaseServices.Surface)trans.GetObject(PrEntRes.ObjectId, OpenMode.ForRead);
                }

                //Obtinerea punctelor suprafetei
                List <string> puncte = new List <string>();
                int           nr     = 0;
                if (suprafata is Autodesk.Civil.DatabaseServices.TinSurface)
                {
                    Autodesk.Civil.DatabaseServices.TinSurface suprafTIN = (Autodesk.Civil.DatabaseServices.TinSurface)suprafata;
                    //Autodesk.Civil.DatabaseServices.TinSurfaceVertexCollection vertecsiTIN = suprafTIN.Vertices;
                    foreach (Autodesk.Civil.DatabaseServices.TinSurfaceVertex V in suprafTIN.Vertices)
                    {
                        nr = nr + 1;
                        puncte.Add(nr.ToString() + "," + V.Location.ToString().Replace("(", "").Replace(")", "") + "," + suprafata.Name);
                    }
                }
                else if (suprafata is Autodesk.Civil.DatabaseServices.GridSurface)
                {
                    Autodesk.Civil.DatabaseServices.GridSurface suprafGRID = (Autodesk.Civil.DatabaseServices.GridSurface)suprafata;
                    foreach (Autodesk.Civil.DatabaseServices.GridSurfaceVertex V in suprafGRID.Vertices)
                    {
                        nr = nr + 1;
                        puncte.Add(nr.ToString() + "," + V.Location.ToString().Replace("(", "").Replace(")", "") + "," + suprafata.Name);
                    }
                }
                else
                {
                    ed.WriteMessage("\nSurface type not supported! Aborting.");
                    return;
                }

                ////TEST: se listeaza punctele
                //foreach(string p in puncte) ed.WriteMessage(p);

                //Selectia fisierului .csv si scrierea punctelor
                PromptSaveFileOptions PrFileOpt = new PromptSaveFileOptions("\nSelect file for point export: ");
                PrFileOpt.Filter = ("CSV file (*.csv)|*.csv");
                string caleDocAcad = HostApplicationServices.Current.FindFile(acadDoc.Name, acadDoc.Database, FindFileHint.Default);
                //PrFileOpt.InitialDirectory = caleDocAcad.Remove(caleDocAcad.LastIndexOf("\\");
                PrFileOpt.InitialFileName = caleDocAcad.Replace(caleDocAcad.Substring(caleDocAcad.LastIndexOf('.')), ".csv");
                ed.WriteMessage(PrFileOpt.InitialDirectory);

                PromptFileNameResult PrFileRes = ed.GetFileNameForSave(PrFileOpt);
                if (PrFileRes.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nPoint export unsuccessful!");
                    return;
                }
                StreamWriter scriitor = new StreamWriter(PrFileRes.StringResult);
                foreach (string p in puncte)
                {
                    scriitor.WriteLine(p);
                }
                scriitor.Dispose();
            }
        }