Example #1
0
        private void defineUndercuts()
        {
            if (panelBase.Panel.undercuts?.undercut?.Count() > 0)
             {
            //var undercuts = panelBase.Panel.undercuts?.undercut?.Select(u => new { posi = u.posi, width = u.width, height = u.height });
            //var outsides = panelBase.Panel.outsides?.outside?.Select(b => new { posi = b.posi, width = b.width, height = b.height });
            //var cuts = undercuts == null ? outsides : outsides?.Union(undercuts) ?? undercuts;
            //if (cuts != null)

            foreach (var undercut in panelBase.Panel.undercuts.undercut)
            {
               Point2d ptMin = new Point2d(undercut.posi.X, undercut.posi.Y);
               Point2d ptMax = new Point2d(undercut.posi.X + undercut.width, undercut.posi.Y + undercut.height);
               var ext2d = new Extents2d(ptMin, ptMax);

               undercutsExt.Add(ext2d);
               panelBase.Openings.Add(new Extents3d
                  (
                     ext2d.MinPoint.Convert3d(),
                     ext2d.MaxPoint.Convert3d()
                  )
               );
            }
             }
        }
Example #2
0
        public void MultipleProfileOnCurve()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            Topography.SurfaceType surface = Topography.PickSurface();
            if (surface == Topography.SurfaceType.None)
            {
                return;
            }
            if (!Topography.EnsureSurfaceNotEmpty(surface))
            {
                return;
            }

            // Pick center alignment
            bool     flag    = true;
            ObjectId curveId = ObjectId.Null;

            while (flag)
            {
                PromptEntityOptions entityOpts = new PromptEntityOptions("\nAna eksen [Seçenekler]: ", "Settings");
                entityOpts.SetRejectMessage("\nSelect a curve.");
                entityOpts.AddAllowedClass(typeof(Curve), false);
                PromptEntityResult entityRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entityOpts);
                if (entityRes.Status == PromptStatus.Keyword)
                {
                    ShowSettings();
                }
                else if (entityRes.Status == PromptStatus.OK)
                {
                    curveId = entityRes.ObjectId;
                    break;
                }
                else if (entityRes.Status == PromptStatus.Cancel)
                {
                    return;
                }
            }

            // Pick other alignments
            IEnumerable <ObjectId> curveIds = SelectEntititesProfile();

            using (Transaction tr = db.TransactionManager.StartTransaction())
                using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                {
                    Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;

                    ObjectId textStyleId = ObjectId.Null;
                    using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead))
                    {
                        if (tt.Has(TextStyleName))
                        {
                            textStyleId = tt[TextStyleName];
                        }
                    }

                    // Project curve onto surface
                    Topography        topo   = Topography.Instance;
                    Curve             center = tr.GetObject(curveId, OpenMode.ForRead) as Curve;
                    Point2dCollection points = topo.ProfileOnCurve(center, surface);

                    // Project other curves
                    Dictionary <Entity, Point2dCollection> otherPoints = new Dictionary <Entity, Point2dCollection>();
                    foreach (ObjectId id in curveIds)
                    {
                        Curve             curve   = tr.GetObject(id, OpenMode.ForRead) as Curve;
                        Point2dCollection spoints = topo.ProfileOnCurve(curve, center, surface);
                        otherPoints.Add(curve, spoints);
                    }

                    // Base point for profile drawing
                    PromptPointResult pointRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nProfil başlangıcı: ");
                    if (pointRes.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    Point3d basePt = pointRes.Value;

                    if (points.Count > 0)
                    {
                        // Limits
                        Extents2d ex = AcadUtility.AcadGeometry.Limits(points);
                        foreach (Point2dCollection pts in otherPoints.Values)
                        {
                            ex = AcadUtility.AcadGeometry.Limits(ex, pts);
                        }

                        // Base level for profile drawing
                        PromptDoubleOptions levelOpts = new PromptDoubleOptions("\nProfil baz kotu: ");
                        levelOpts.DefaultValue    = Math.Floor(ex.MinPoint.Y / ProfileGridV) * ProfileGridV;
                        levelOpts.UseDefaultValue = true;
                        PromptDoubleResult levelRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(levelOpts);
                        if (pointRes.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        double startLevel = levelRes.Value;
                        double endLevel   = Math.Ceiling(ex.MaxPoint.Y / ProfileGridV + 1) * ProfileGridV;

                        // Base chainage for profile drawing
                        double startCh = 0;
                        flag = true;
                        while (flag)
                        {
                            PromptStringOptions chOpts = new PromptStringOptions("\nProfil baz KM: ");
                            chOpts.DefaultValue    = AcadUtility.AcadText.ChainageToString(0, Precision);
                            chOpts.UseDefaultValue = true;
                            PromptResult chRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetString(chOpts);
                            if (chRes.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            if (AcadUtility.AcadText.TryChainageFromString(chRes.StringResult, out startCh))
                            {
                                break;
                            }
                        }
                        double endCh = Math.Ceiling((startCh + ex.MaxPoint.X) / ProfileGridH) * ProfileGridH;

                        // Draw grid
                        IEnumerable <Entity> entities = DrawProfileFrame(db, basePt, startCh, startLevel, endCh, endLevel, ProfileGridH, ProfileGridV, ProfileVScale, TextHeight, Precision, textStyleId);
                        foreach (Entity ent in entities)
                        {
                            ent.TransformBy(ucs2wcs);
                            btr.AppendEntity(ent);
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }

                        // Draw center profile
                        ObjectId          profileLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, "Profil_Eksen", Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 5));
                        Point2dCollection trPoints       = new Point2dCollection(points.Count);
                        foreach (Point2d pt in points)
                        {
                            trPoints.Add(new Point2d(basePt.X + pt.X, basePt.Y + (pt.Y - startLevel) * ProfileVScale));
                        }
                        Polyline pline = AcadUtility.AcadEntity.CreatePolyLine(db, false, trPoints);
                        AcadUtility.AcadEntity.MatchEntity(center, pline);
                        pline.LayerId = profileLayerId;
                        pline.TransformBy(ucs2wcs);
                        btr.AppendEntity(pline);
                        tr.AddNewlyCreatedDBObject(pline, true);

                        // Draw other profiles
                        foreach (KeyValuePair <Entity, Point2dCollection> item in otherPoints)
                        {
                            Entity            en        = item.Key;
                            Point2dCollection spoints   = item.Value;
                            Point2dCollection trsPoints = new Point2dCollection(points.Count);
                            foreach (Point2d pt in spoints)
                            {
                                trsPoints.Add(new Point2d(basePt.X + pt.X, basePt.Y + (pt.Y - startLevel) * ProfileVScale));
                            }
                            Polyline spline = AcadUtility.AcadEntity.CreatePolyLine(db, false, trsPoints);
                            AcadUtility.AcadEntity.MatchEntity(en, spline);
                            spline.LayerId = profileLayerId;
                            spline.TransformBy(ucs2wcs);

                            btr.AppendEntity(spline);
                            tr.AddNewlyCreatedDBObject(spline, true);
                        }
                    }

                    tr.Commit();
                }
        }
Example #3
0
 /// <summary>
 /// Gets a value indicating whether the specified point is inside the extents.
 /// </summary>
 /// <param name="pt">The instance to which the method applies.</param>
 /// <param name="extents">The extents 2d supposed to contain the point.</param>
 /// <returns>true if the point is inside the extents; otherwise, false.</returns>
 public static bool IsInside(this Point2d pt, Extents2d extents)
 {
     return
         pt.X >= extents.MinPoint.X &&
         pt.Y >= extents.MinPoint.Y &&
         pt.X <= extents.MaxPoint.X &&
         pt.Y <= extents.MaxPoint.Y;
 }
Example #4
0
        public void PlotTitleBlock(Document acDoc, Transaction acTrans, BlockTableRecord acBlkTblRecSpc, Extents2d PlotArea, string path, string PlotDevice, string PlotStyle, string CanonicalMediaName)
        {
            Database acCurDb = acDoc.Database;

            //string folder = DirectoryFolder(ac.Database.OriginalFileName);
            //string filename = DocumentShortName(ac.Database.OriginalFileName) + ".pdf";
            //Application.ShowAlertDialog(path);
            Application.SetSystemVariable("BACKGROUNDPLOT", 0);

            Layout acLayout = (Layout)acTrans.GetObject(acBlkTblRecSpc.LayoutId, OpenMode.ForRead);

            PlotInfo acPtInfo = new PlotInfo();

            acPtInfo.Layout = acLayout.ObjectId;

            PlotSettings acPtSet = new PlotSettings(acLayout.ModelType);

            acPtSet.CopyFrom(acLayout);
            if (!acPtSet.PlotPlotStyles)
            {
                acPtSet.PlotPlotStyles = true;
            }
            //if (!acPtSet.ScaleLineweights) acPtSet.ScaleLineweights = true;
            if (acPtSet.ShadePlotResLevel != ShadePlotResLevel.Maximum)
            {
                acPtSet.ShadePlotResLevel = ShadePlotResLevel.Maximum;
            }

            PlotSettingsValidator acPtSetVlr = PlotSettingsValidator.Current;

            //acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
            //Application.ShowAlertDialog(acPlDev);
            acPtSetVlr.SetPlotConfigurationName(acPtSet, PlotDevice, null);
            acPtSetVlr.RefreshLists(acPtSet);
            acPtSetVlr.SetPlotWindowArea(acPtSet, PlotArea);
            acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
            acPtSetVlr.SetPlotWindowArea(acPtSet, PlotArea);
            acPtSetVlr.SetUseStandardScale(acPtSet, true);
            acPtSetVlr.SetStdScaleType(acPtSet, StdScaleType.ScaleToFit);
            acPtSetVlr.SetPlotCentered(acPtSet, true);
            acPtSetVlr.SetCurrentStyleSheet(acPtSet, PlotStyle);
            //acPtSetVlr.SetCurrentStyleSheet(acPtSet, "monochrome.ctb");

            //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_full_bleed_A1_(594.00_x_841.00_MM)");
            //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_A1_(594.00_x_841.00_MM)");
            acPtSetVlr.SetPlotConfigurationName(acPtSet, PlotDevice, CanonicalMediaName);
            Point2d acPSize = acPtSet.PlotPaperSize;

            if (acPSize.X > acPSize.Y)
            {
                acPtSetVlr.SetPlotRotation(acPtSet, PlotRotation.Degrees000);
            }
            else
            {
                acPtSetVlr.SetPlotRotation(acPtSet, PlotRotation.Degrees090);
            }

            //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWF6 ePlot.pc3", "ANSI_A_(8.50_x_11.00_Inches)");
            acPtInfo.OverrideSettings           = acPtSet;
            LayoutManager.Current.CurrentLayout = acLayout.LayoutName;

            //IAcSmEnumComponent

            PlotInfoValidator acPtInfoVlr = new PlotInfoValidator();

            acPtInfoVlr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
            acPtInfoVlr.Validate(acPtInfo);



            //Check if plot in process
            if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
            {
                using (PlotEngine acPtEng = PlotFactory.CreatePublishEngine())
                {
                    PlotProgressDialog acPtProgDlg = new PlotProgressDialog(false, 1, true);
                    using (acPtProgDlg)
                    {
                        //Define message when plot start
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Plot Process");
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Process");
                        //acPtProgDlg.set_PlotMsgString(PlotMessageIndex.SheetName, "abc");

                        //Set the process range
                        acPtProgDlg.LowerPlotProgressRange = 0;
                        acPtProgDlg.UpperPlotProgressRange = 100;
                        acPtProgDlg.PlotProgressPos        = 0;

                        //Display the process dialog
                        acPtProgDlg.OnBeginPlot();
                        acPtProgDlg.IsVisible = true;

                        //Start the layout plot
                        acPtEng.BeginPlot(acPtProgDlg, null);

                        //Define the plot output
                        acPtEng.BeginDocument(acPtInfo, acDoc.Name, null, 1, true, @path);
                        //Display the process message
                        acPtProgDlg.set_PlotMsgString(PlotMessageIndex.Status, "Plotting " + acDoc.Name + " - " + acLayout.LayoutName);

                        //Set the sheet process range
                        acPtProgDlg.OnBeginSheet();
                        acPtProgDlg.LowerSheetProgressRange = 0;
                        acPtProgDlg.UpperPlotProgressRange  = 100;
                        acPtProgDlg.SheetProgressPos        = 0;

                        //Plot the first sheet
                        PlotPageInfo acPtPageInfo = new PlotPageInfo();
                        acPtEng.BeginPage(acPtPageInfo, acPtInfo, true, null);
                        //acPtEng.BeginPage(
                        acPtEng.BeginGenerateGraphics(null);
                        acPtEng.EndGenerateGraphics(null);

                        //End plot sheet
                        acPtEng.EndPage(null);
                        acPtProgDlg.SheetProgressPos = 100;
                        acPtProgDlg.OnEndSheet();

                        //End document
                        acPtEng.EndDocument(null);

                        //End plot
                        acPtProgDlg.PlotProgressPos = 100;
                        acPtProgDlg.OnEndPlot();
                        acPtEng.EndPlot(null);
                    }
                }
            }
        }
Example #5
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;
            }
        }
Example #6
0
        public void CreateLayout()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            if (doc == null)
            {
                return;
            }
            var db = doc.Database;
            var ed = doc.Editor;

            var ext = new Extents2d();

            using (var tr = db.TransactionManager.StartTransaction())
            {
                // Create and select a new layout tab
                var id = LayoutManager.Current.CreateAndMakeLayoutCurrent("NewLayout");

                // Open the created layout
                var lay = (Layout)tr.GetObject(id, OpenMode.ForWrite);

                // Make some settings on the layout and get its extents
                lay.SetPlotSettings(
                    //"ISO_full_bleed_2A0_(1189.00_x_1682.00_MM)", // Try this big boy!
                    "ANSI_B_(11.00_x_17.00_Inches)",
                    "monochrome.ctb",
                    "DWF6 ePlot.pc3"
                    );

                ext = lay.GetMaximumExtents();

                lay.ApplyToViewport(tr, 2, vp =>
                {
                    // Size the viewport according to the extents calculated when
                    // we set the PlotSettings (device, page size, etc.)
                    // Use the standard 10% margin around the viewport
                    // (found by measuring pixels on screenshots of Layout1, etc.)
                    vp.ResizeViewport(ext, 0.8);

                    // Adjust the view so that the model contents fit
                    if (ValidDbExtents(db.Extmin, db.Extmax))
                    {
                        vp.FitContentToViewport(new Extents3d(db.Extmin, db.Extmax), 0.9);
                    }

                    // Finally we lock the view to prevent meddling
                    vp.Locked = true;
                }
                                    );

                // Commit the transaction
                tr.Commit();
            }

            // Zoom so that we can see our new layout, again with a little padding

            doc.SendStringToExecute("_.ZOOM _E ", true, false, false);  // AutoCAD 2014
            doc.SendStringToExecute("_.ZOOM .7X ", true, false, false); // AutoCAD 2014
            // ed.Command("_.ZOOM", "_E");  // AutoCAD 2016
            //  ed.Command("_.ZOOM", ".7X"); // AutoCAD 2016
            ed.Regen();
        }
Example #7
0
        /// <summary>
        /// plotting method
        /// </summary>
        /// <param name="pdfFileName"> name</param>
        /// <param name="printModel">print param model</param>
        public static void PlotCurrentLayout(string pdfFileName, PrintModel printModel)
        {
            // Get the current document and database, and start a transaction
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            //short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
            try
            {
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // Reference the Layout Manager
                    LayoutManager acLayoutMgr;
                    acLayoutMgr = LayoutManager.Current;
                    // Get the current layout and output its name in the Command Line window
                    Layout acLayout;
                    acLayout =
                        acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout),
                                          OpenMode.ForRead) as Layout;

                    // Get the PlotInfo from the layout
                    PlotInfo acPlInfo = new PlotInfo();
                    acPlInfo.Layout = acLayout.ObjectId;

                    // Get a copy of the PlotSettings from the layout
                    PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);

                    acPlSet.CopyFrom(acLayout);
                    // Update the PlotSettings object
                    PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                    var sheetList = acPlSetVdr.GetPlotStyleSheetList();
                    //acPlSetVdr.SetCurrentStyleSheet(acPlSet, "monochrome.ctb");

                    Extents2d points = new Extents2d(printModel.BlockPosition, printModel.BlockDimensions);

                    bool isHor = printModel.IsFormatHorizontal();
                    //pdfCreator.GetBlockDimensions();
                    string canonName = printModel.GetCanonNameByWidthAndHeight();

                    //acDoc.Utility.TranslateCoordinates(point1, acWorld, acDisplayDCS, False);
                    acPlSetVdr.SetPlotWindowArea(acPlSet, points);
                    acPlSetVdr.SetPlotType(acPlSet, Db.PlotType.Window);
                    if (!isHor)
                    {
                        acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                    }
                    //else if(canonName =="ISO_full_bleed_A4_(297.00_x_210.00_MM)")
                    //    acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                    else
                    {
                        acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                    }

                    // Set the plot scale
                    acPlSetVdr.SetUseStandardScale(acPlSet, false);
                    acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);
                    // Center the plot
                    acPlSetVdr.SetPlotCentered(acPlSet, true);
                    //acPlSetVdr.SetClosestMediaName(acPlSet,printModel.width,printModel.height,PlotPaperUnit.Millimeters,true);
                    //string curCanonName = PdfCreator.GetLocalNameByAtrrValue(formatValue);
                    acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG_To_PDF_Uzle.pc3", canonName);
                    //acPlSetVdr.SetCanonicalMediaName(acPlSet, curCanonName);

                    // Set the plot device to use

                    // Set the plot info as an override since it will
                    // not be saved back to the layout
                    acPlInfo.OverrideSettings = acPlSet;
                    // Validate the plot info
                    PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                    acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                    acPlInfoVdr.Validate(acPlInfo);

                    // Check to see if a plot is already in progress
                    if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                    {
                        using (PlotEngine acPlEng = PlotFactory.CreatePublishEngine())
                        {
                            // Track the plot progress with a Progress dialog
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, 1, true);
                            using (acPlProgDlg)
                            {
                                // Define the status messages to display when plotting starts
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Plot Progress");
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption,
                                                              "Sheet Set Progress");
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                                // Set the plot progress range
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                // Display the Progress dialog
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                // Start to plot the layout
                                acPlEng.BeginPlot(acPlProgDlg, null);
                                // Define the plot output
                                string filename = Path.Combine(Path.GetDirectoryName(acDoc.Name), pdfFileName);
                                Active.Editor.WriteMessage(filename);

                                acPlEng.BeginDocument(acPlInfo, acDoc.Name, null, 1, true, filename);
                                // Display information about the current plot
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status,
                                                              "Plotting: " + acDoc.Name + " - " + acLayout.LayoutName);
                                // Set the sheet progress range
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                // Plot the first sheet/layout
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng.BeginGenerateGraphics(null);
                                acPlEng.EndGenerateGraphics(null);
                                // Finish plotting the sheet/layout
                                acPlEng.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                // Finish plotting the document
                                acPlEng.EndDocument(null);
                                // Finish the plot
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng.EndPlot(null);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Application.ShowAlertDialog(e.Message);
            }
        }
Example #8
0
 public static Extents2d Inflate(this Extents2d extents, int size)
 {
     return(new Extents2d(extents.MinPoint.X - size, extents.MinPoint.Y - size,
                          extents.MaxPoint.X + size, extents.MaxPoint.Y + size));
 }
Example #9
0
        void PrintPage(object sender, PrintPageEventArgs ev)
        {
            if (m_pPrinterDevice != null)
            {
                using (DBObject pVpObj = Aux.active_viewport_id(database).GetObject(OpenMode.ForWrite))
                {
                    using (AbstractViewportData pAV = new AbstractViewportData(pVpObj))
                    {
                        Teigha.GraphicsSystem.View pGSView = pAV.GsView;

                        PrintDocument prDoc = (PrintDocument)sender;

                        // Get printer paper info
                        Double dPrinterWidth  = ev.PageBounds.Width;
                        Double dPrinterHeight = ev.PageBounds.Height;
                        Double dLogPixelX     = ev.PageSettings.PrinterResolution.X; //dot per inch
                        Double dLogPixelY     = ev.PageSettings.PrinterResolution.Y; //dot per inch
                        Double kMmPerInch     = 25.4;
                        Double kMmPerHInch    = 0.254;
                        Double koeffX         = dLogPixelX / kMmPerInch;
                        Double koeffY         = dLogPixelY / kMmPerInch;

                        Layout  pLayout      = (Layout)m_pPrinterDevice.LayoutId.GetObject(OpenMode.ForRead);
                        Boolean bScaledToFit = pLayout.UseStandardScale && (StdScaleType.ScaleToFit == pLayout.StdScaleType);
                        Boolean bCentered    = pLayout.PlotCentered;
                        Boolean bMetric      = (pLayout.PlotPaperUnits != PlotPaperUnit.Inches);
                        Boolean bPrintLW     = pLayout.PrintLineweights || pLayout.ShowPlotStyles;

                        Point2d offsets = pLayout.PlotOrigin; // in mm

                        Extents2d ex2d          = pLayout.PlotPaperMargins;
                        Double    dLeftMargin   = ex2d.MinPoint.X; // in mm
                        Double    dRightMargin  = ex2d.MaxPoint.X; // in mm
                        Double    dTopMargin    = ex2d.MinPoint.Y; // in mm
                        Double    dBottomMargin = ex2d.MaxPoint.Y; // in mm
                        PlotType  plotType      = pLayout.PlotType;

                        PlotRotation plotRotation = pLayout.PlotRotation;
                        if (plotRotation == PlotRotation.Degrees090 || plotRotation == PlotRotation.Degrees270)
                        {
                            plotRotation = (plotRotation == PlotRotation.Degrees090) ? PlotRotation.Degrees270 : PlotRotation.Degrees090;
                        }

                        switch (plotRotation)
                        {
                        case PlotRotation.Degrees090:
                            Swap <Double>(dTopMargin, dRightMargin);
                            Swap <Double>(dBottomMargin, dLeftMargin);
                            Swap <Double>(dBottomMargin, dTopMargin);
                            Swap <Double>(dTopMargin, dRightMargin);
                            offsets = new Point2d(-offsets.X, -offsets.Y);
                            break;

                        case PlotRotation.Degrees180:
                            Swap <Double>(dRightMargin, dLeftMargin);
                            offsets = new Point2d(-offsets.X, -offsets.Y);
                            break;

                        case PlotRotation.Degrees270:
                            Swap <Double>(dTopMargin, dRightMargin);
                            Swap <Double>(dBottomMargin, dLeftMargin);
                            Swap <Double>(dBottomMargin, dTopMargin);
                            offsets = new Point2d(offsets.X, offsets.Y);
                            break;
                        }

                        // Get scale factor
                        double factor;
                        if (pLayout.UseStandardScale)
                        {
                            factor = pLayout.StdScale;
                        }
                        else
                        {
                            CustomScale scale = pLayout.CustomPrintScale;
                            factor = scale.Numerator / scale.Denominator;
                        }

                        // Calculate paper drawable area using margins from layout (in mm).
                        Double drx1 = (ev.MarginBounds.Left * kMmPerHInch + dLeftMargin);                  // in mm
                        Double drx2 = (ev.MarginBounds.Width * kMmPerHInch - dLeftMargin - dRightMargin);  // in mm
                        Double dry1 = (ev.MarginBounds.Top * kMmPerHInch + dTopMargin);                    // in mm
                        Double dry2 = (ev.MarginBounds.Height * kMmPerHInch - dTopMargin - dBottomMargin); // in mm

                        Boolean        bType           = (plotType == PlotType.Display || plotType == PlotType.Layout);
                        AbstractViewPE pAbstractViewPE = new AbstractViewPE(bType ? pViewDr : pGSView);

                        // set LineWeight scale factor for model space
                        if (bPrintLW && database.TileMode)
                        {
                            Teigha.GraphicsSystem.View pTo = m_pPrinterDevice.ViewAt(0);
                            pTo.LineweightToDcScale = Math.Max(dLogPixelX, dLogPixelY) / kMmPerInch * 0.01;
                        }

                        Point3d  viewTarget     = pAbstractViewPE.Target;
                        Point3d  viewportCenter = pAbstractViewPE.Target;      // in plotPaperUnits
                        Boolean  isPerspective  = pAbstractViewPE.IsPerspective;
                        Double   viewportH      = pAbstractViewPE.FieldHeight; // in plotPaperUnits
                        Double   viewportW      = pAbstractViewPE.FieldWidth;  // in plotPaperUnits
                        Vector3d viewDir        = pAbstractViewPE.Direction;   // in plotPaperUnits
                        Vector3d upV            = pAbstractViewPE.UpVector;    // in plotPaperUnits
                        Matrix3d eyeToWorld     = pAbstractViewPE.EyeToWorld;
                        Matrix3d WorldToeye     = pAbstractViewPE.WorldToEye;

                        Boolean isPlanView = viewDir.GetNormal().Equals(Vector3d.ZAxis);
                        Point3d oldTarget  = viewTarget;

                        Double fieldWidth = viewportW, fieldHeight = viewportH;

                        if (plotType == PlotType.Display)
                        {
                            viewTarget  = viewportCenter;
                            fieldWidth  = viewportW;
                            fieldHeight = viewportH;
                        }
                        else if (plotType == PlotType.Extents || (plotType == PlotType.Limits && !isPlanView))
                        {
                            BoundBlock3d extents = new BoundBlock3d();
                            if (pAbstractViewPE.GetViewExtents(extents)) // pIter also skip 'off layers'
                            {
                                extents.TransformBy(eyeToWorld);
                                viewTarget = (extents.GetMinimumPoint() + extents.GetMaximumPoint().GetAsVector()) / 2.0;
                                extents.TransformBy(WorldToeye);

                                fieldWidth  = Math.Abs(extents.GetMaximumPoint().X - extents.GetMinimumPoint().X);
                                fieldHeight = Math.Abs(extents.GetMaximumPoint().Y - extents.GetMinimumPoint().Y);
                            }
                        }
                        else if (plotType == PlotType.View)
                        {
                            viewTarget  = viewportCenter;
                            fieldWidth  = viewportW;
                            fieldHeight = viewportH;
                        }
                        else if (plotType == PlotType.Limits)
                        {
                            fieldWidth  = (drx2 - drx1) / factor; // drx in mm -> fieldWidth in mm
                            fieldHeight = (dry2 - dry1) / factor;

                            viewTarget = new Point3d(fieldWidth / 2.0 - offsets.X / factor, fieldHeight / 2.0 - offsets.Y / factor, 0); // in mm
                            if (!bMetric)
                            {
                                viewTarget  /= kMmPerInch; // must be in plotpaper units
                                fieldWidth  /= kMmPerInch;
                                fieldHeight /= kMmPerInch;
                            }

                            bCentered = bScaledToFit = false; // kLayout doesn't support pIter.
                        }

                        if (plotType != PlotType.View)
                        {
                            viewTarget = viewTarget.OrthoProject(new Plane(oldTarget, viewDir));
                        }

                        pGSView.SetView(viewTarget + viewDir, viewTarget, upV, fieldWidth, fieldHeight, isPerspective ? Teigha.GraphicsSystem.Projection.Perspective : Teigha.GraphicsSystem.Projection.Parallel);

                        if (!bMetric)
                        {
                            fieldWidth  *= kMmPerInch;
                            fieldHeight *= kMmPerInch;
                        }

                        if (bScaledToFit)
                        {
                            factor = Math.Min((drx2 - drx1) / fieldWidth, (dry2 - dry1) / fieldHeight);
                        }

                        if (bCentered) // Offset also can be incorectly saved.
                        {
                            offsets = new Point2d(((drx2 - drx1) - fieldWidth * factor) / 2.0,
                                                  ((dry2 - dry1) - fieldHeight * factor) / 2.0);

                            if (plotRotation == PlotRotation.Degrees090 || plotRotation == PlotRotation.Degrees180)
                            {
                                offsets = new Point2d(-offsets.X, -offsets.Y);
                            }
                        }

                        pGSView.Viewport = new Extents2d(0, 0, 1, 1);

                        // Calculate viewport rect in printer units
                        //int x1 = (int)((offsets.X + drx1) * koeffX);
                        //int x2 = (int)((offsets.X + drx2) * koeffX);
                        //int y1 = (int)((-offsets.Y + dry1) * koeffY);
                        //int y2 = (int)((-offsets.Y + dry2) * koeffY);
                        int x1 = (int)(drx1 * koeffX);
                        int x2 = (int)(drx2 * koeffX);
                        int y1 = (int)(dry1 * koeffY);
                        int y2 = (int)(dry2 * koeffY);

                        Rectangle viewportRect = new Rectangle(x1, y1, x2, y2);
                        m_pPrinterDevice.OnSize(viewportRect);
                        if (m_pPrinterDevice.UnderlyingDevice.Properties.Contains("WindowHDC"))
                        {
                            m_pPrinterDevice.UnderlyingDevice.Properties.AtPut("WindowHDC", new RxVariant((Int32)ev.Graphics.GetHdc()));
                        }
                        m_pPrinterDevice.Update();

                        pAbstractViewPE.Dispose();
                        pLayout.Dispose();
                    }
                }
            }
        }
        private void Create3dProfile(object arg)
        {
            try
            {
                if (doc != null)
                {
                    List <ObjectId> toHighlight = new List <ObjectId>();

                    using (doc.LockDocument())
                    {
                        Editor   ed = doc.Editor;
                        Database db = doc.Database;

                        using (Transaction tr = db.TransactionManager.StartTransaction())
                        {
                            //найти координату X начала профиля (крайнюю левую)
                            double          minx        = double.PositiveInfinity;
                            List <ObjectId> allSelected = new List <ObjectId>(soilHatchIds);
                            foreach (ObjectId id in allSelected)
                            {
                                Entity ent = null;
                                try
                                {
                                    ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                                }
                                catch (Autodesk.AutoCAD.Runtime.Exception) { continue; }
                                Extents3d?ext = ent.Bounds;
                                if (ext != null)
                                {
                                    Point3d minPt = ext.Value.MinPoint;
                                    if (minx > minPt.X)
                                    {
                                        minx = minPt.X;
                                    }
                                }
                            }


                            //Штриховки должны быть заранее раскиданы по слоям в соответствии с ИГЭ!

                            //пересчет всех точек штриховок в координаты:
                            //X - положение отностиельно начала профиля с учетом горизонтального масштаба профиля,
                            //Y - отметка расчитанная согласно базовой отметке с учетом вертикального масштаба профиля
                            Matrix2d transform =
                                new Matrix2d(new double[]
                            {
                                HorScaling, 0, 0,
                                0, VertScaling, 0,
                                0, 0, 1
                            })
                                * Matrix2d.Displacement(new Vector2d(-minx, -ElevBasePoint.Value.Y + ElevationInput / VertScaling));

                            C5.IntervalHeap <HatchEvent> eventQueue            = new C5.IntervalHeap <HatchEvent>();
                            List <HatchData>             allHatchData          = new List <HatchData>();
                            List <Point2dCollection>     selfintersectingLoops = new List <Point2dCollection>();
                            foreach (ObjectId id in soilHatchIds)
                            {
                                //получить все точки штриховок с учетом возможных дуг, сплайнов и проч
                                //Для каждой штриховки создается набор композитных кривых, состоящих из линейных сегментов
                                Hatch hatch = null;
                                try
                                {
                                    hatch = (Hatch)tr.GetObject(id, OpenMode.ForRead);
                                }
                                catch (Autodesk.AutoCAD.Runtime.Exception) { continue; }
                                List <CompositeCurve2d>  boundaries   = new List <CompositeCurve2d>();
                                List <Extents2d>         extends      = new List <Extents2d>();
                                List <Point2dCollection> ptsCollList  = new List <Point2dCollection>();
                                List <List <double> >    ptParamsList = new List <List <double> >();
                                for (int i = 0; i < hatch.NumberOfLoops; i++)
                                {
                                    HatchLoop hl = hatch.GetLoopAt(i);
                                    if (!hl.LoopType.HasFlag(HatchLoopTypes.SelfIntersecting) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.Textbox) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.TextIsland) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.NotClosed))
                                    {
                                        List <Curve2d>   curves = Utils.GetHatchLoopCurves(hl);
                                        List <Curve2d>   compositeCurveElems = new List <Curve2d>();
                                        double           _minx         = double.PositiveInfinity;
                                        double           _miny         = double.PositiveInfinity;
                                        double           _maxx         = double.NegativeInfinity;
                                        double           _maxy         = double.NegativeInfinity;
                                        Action <Point2d> updateExtends = new Action <Point2d>(p =>
                                        {
                                            _minx = p.X < _minx ? p.X : _minx;
                                            _miny = p.Y < _miny ? p.Y : _miny;
                                            _maxx = p.X > _maxx ? p.X : _maxx;
                                            _maxy = p.Y > _maxy ? p.Y : _maxy;
                                        });

                                        Point2dCollection ptsColl   = new Point2dCollection();
                                        List <double>     ptParams  = new List <double>();
                                        double            currParam = 0;
                                        foreach (Curve2d c in curves)
                                        {
                                            if (!(c is LineSegment2d))
                                            {
                                                Interval         interval  = c.GetInterval();
                                                PointOnCurve2d[] samplePts = c.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.02);

                                                Point2d[] pts = samplePts.Select(p => transform * p.Point).ToArray();
                                                for (int n = 0; n < pts.Length - 1; n++)
                                                {
                                                    LineSegment2d lineSeg = new LineSegment2d(pts[n], pts[n + 1]);
                                                    compositeCurveElems.Add(lineSeg);

                                                    ptsColl.Add(pts[n]);
                                                    ptParams.Add(currParam);
                                                    updateExtends(pts[n]);
                                                    currParam += lineSeg.Length;
                                                }
                                            }
                                            else
                                            {
                                                LineSegment2d lineSeg = (LineSegment2d)c;
                                                lineSeg.TransformBy(transform);
                                                compositeCurveElems.Add(lineSeg);

                                                ptsColl.Add(lineSeg.StartPoint);
                                                ptParams.Add(currParam);
                                                updateExtends(lineSeg.StartPoint);
                                                currParam += lineSeg.Length;
                                            }
                                        }


                                        CompositeCurve2d boundary = new CompositeCurve2d(compositeCurveElems.ToArray());
                                        Extents2d        ext      = new Extents2d(_minx, _miny, _maxx, _maxy);
                                        boundaries.Add(boundary);
                                        ptsCollList.Add(ptsColl);
                                        ptParamsList.Add(ptParams);
                                        extends.Add(ext);
                                    }
                                }

                                //контуры штриховок не могут иметь самопересечений!
                                #region Проверка на пересечения
                                //проверка на самопересечения
                                //bool badBoundaries = false;
                                HashSet <int> badBoundaries   = new HashSet <int>();
                                HashSet <int> splitBoundaries = new HashSet <int>();//Если 2 контура в одной штриховке пересекаются, то разносить их по разным штриховкам
                                //List<HatchData> decomposeHatchData = new List<HatchData>();//TODO: самопересекающиеся полигоны нужно разбить на отдельные по количеству самопересечний.

                                for (int i = 0; i < boundaries.Count; i++)
                                {
                                    CompositeCurve2d        b           = boundaries[i];
                                    CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(b, b);
                                    if (intersector.NumberOfIntersectionPoints > 0)
                                    {
                                        //если происходит только наложение???
                                        badBoundaries.Add(i);
                                        selfintersectingLoops.Add(ptsCollList[i]);
                                    }
                                }

                                if (boundaries.Count > 1)
                                {
                                    //проверка на взаимные пересечения.
                                    //Исп RBush для того чтобы избежать проверки на пересечение каждого с каждым и квадратичной сложности
                                    //(работает только если контуры разнесены)
                                    //Не брать в расчет пересечения по касательной
                                    RBush <Spatial> boundariesRBush = new RBush <Spatial>();
                                    List <Spatial>  spatialData     = new List <Spatial>();
                                    for (int i = 0; i < extends.Count; i++)
                                    {
                                        spatialData.Add(new Spatial(extends[i], i));
                                    }
                                    boundariesRBush.BulkLoad(spatialData);
                                    foreach (Spatial s in spatialData)
                                    {
                                        IReadOnlyList <Spatial> nearestNeighbors = boundariesRBush.Search(s.Envelope);
                                        if (nearestNeighbors.Count > 1)
                                        {
                                            CompositeCurve2d thisCurve = boundaries[(int)s.Obj];
                                            foreach (Spatial n in nearestNeighbors)
                                            {
                                                if (!s.Equals(n))
                                                {
                                                    CompositeCurve2d        otherCurve = boundaries[(int)n.Obj];
                                                    CurveCurveIntersector2d intersector
                                                        = new CurveCurveIntersector2d(thisCurve, otherCurve);
                                                    if (intersector.NumberOfIntersectionPoints > 0 ||
                                                        intersector.OverlapCount > 0)
                                                    {
                                                        bool matches = false;
                                                        //Проверить, что кривые не накладываются друг на друга по всей длине (то есть полностью совпадают)
                                                        if (intersector.OverlapCount > 0)
                                                        {
                                                            //сумма длин всех интервалов перекрытия равна общей длине кривой
                                                            double thisCurveOverlapLength  = 0;
                                                            double otherCurveOverlapLength = 0;
                                                            for (int i = 0; i < intersector.OverlapCount; i++)
                                                            {
                                                                Interval[] intervals           = intersector.GetOverlapRanges(i);
                                                                Interval   thisOverlapInterval = intervals[0];
                                                                thisCurveOverlapLength += thisOverlapInterval.Length;
                                                                Interval otherOverlapInterval = intervals[1];
                                                                otherCurveOverlapLength += otherOverlapInterval.Length;
                                                            }

                                                            Interval thisCurveInterval  = thisCurve.GetInterval();
                                                            Interval otherCurveInterval = otherCurve.GetInterval();

                                                            if (Utils.LengthIsEquals(thisCurveOverlapLength, thisCurveInterval.Length) &&
                                                                Utils.LengthIsEquals(otherCurveOverlapLength, otherCurveInterval.Length))
                                                            {
                                                                matches = true;
                                                            }
                                                        }

                                                        if (!matches)
                                                        {
                                                            splitBoundaries.Add((int)s.Obj);
                                                            splitBoundaries.Add((int)n.Obj);
                                                        }
                                                        else
                                                        {
                                                            badBoundaries.Add((int)s.Obj);
                                                            badBoundaries.Add((int)n.Obj);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                splitBoundaries.ExceptWith(badBoundaries);
                                List <HatchData> splitHatchData = new List <HatchData>();
                                if (badBoundaries.Count > 0 || splitBoundaries.Count > 0)
                                {
                                    List <CompositeCurve2d>  boundariesClear   = new List <CompositeCurve2d>();
                                    List <Extents2d>         extendsClear      = new List <Extents2d>();
                                    List <Point2dCollection> ptsCollListClear  = new List <Point2dCollection>();
                                    List <List <double> >    ptParamsListClear = new List <List <double> >();

                                    for (int i = 0; i < boundaries.Count; i++)
                                    {
                                        if (!badBoundaries.Contains(i) && !splitBoundaries.Contains(i))
                                        {
                                            boundariesClear.Add(boundaries[i]);
                                            extendsClear.Add(extends[i]);
                                            ptsCollListClear.Add(ptsCollList[i]);
                                            ptParamsListClear.Add(ptParamsList[i]);
                                        }
                                    }

                                    foreach (int index in splitBoundaries)
                                    {
                                        splitHatchData.Add(new HatchData(
                                                               new HatchNestingNode(
                                                                   boundaries[index],
                                                                   extends[index],
                                                                   ptsCollList[index],
                                                                   ptParamsList[index], hatch)));
                                    }


                                    boundaries   = boundariesClear;
                                    extends      = extendsClear;
                                    ptsCollList  = ptsCollListClear;
                                    ptParamsList = ptParamsListClear;
                                }
                                #endregion

                                //определяется вложенность контуров штриховки
                                //ЕСЛИ ШТРИХОВКА СОСТОИТ ИЗ 2 И БОЛЕЕ КОНТУРОВ, КОТОРЫЕ НЕ ВЛОЖЕНЫ ДРУГ В ДРУГА,
                                //ТО ЭТИ КОНТУРЫ ДОЛЖНЫ РАССМАТРИВАТЬСЯ КАК ОТДЕЛЬНЫЕ ШТРИХОВКИ!!!
                                HatchNestingTree hatchNestingTree
                                    = new HatchNestingTree(boundaries, extends, ptsCollList, ptParamsList, hatch);
                                List <HatchData> currHatchData = hatchNestingTree.GetHatchData();
                                currHatchData.AddRange(splitHatchData);//добавить контуры, полученные из взаимно пересекающихся контуров
                                //currHatchData.AddRange(decomposeHatchData);

                                allHatchData.AddRange(currHatchData);

                                //Каждая штриховка имеет диапазон по X от начала до конца по оси.
                                //В общую очередь событий сохраняются события начала и конца штриховки
                                foreach (HatchData hd in currHatchData)
                                {
                                    hd.AddEventsToQueue(eventQueue);
                                }
                            }



                            //Трассу разбить на отрезки, на которых будут вставлены прямолинейные сегменты штриховок
                            Polyline alignmentPoly = null;
                            try
                            {
                                alignmentPoly = (Polyline)tr.GetObject(AlignmentPolyId, OpenMode.ForRead);
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception)
                            {
                                return;
                            }
                            int segments = alignmentPoly.NumberOfVertices - 1;
                            List <AlignmentSegment>   alignmentSegments   = new List <AlignmentSegment>();
                            Action <Point2d, Point2d> addAlignmentSegment = new Action <Point2d, Point2d>((p0, p1) =>
                            {
                                double start = alignmentPoly.GetDistAtPoint(new Point3d(p0.X, p0.Y, 0));
                                double end   = alignmentPoly.GetDistAtPoint(new Point3d(p1.X, p1.Y, 0));
                                if (Math.Abs(start - end) > Tolerance.Global.EqualPoint)//TODO: Это спорный момент - ведь может быть большое множество очень коротких участков подряд!
                                {
                                    Vector2d startDir = p1 - p0;
                                    alignmentSegments.Add(new AlignmentSegment(start, end, p0, startDir));
                                }
                            });
                            for (int i = 0; i < segments; i++)
                            {
                                SegmentType segmentType = alignmentPoly.GetSegmentType(i);
                                Point2d     startLoc    = alignmentPoly.GetPoint2dAt(i);
                                Point2d     endLoc      = alignmentPoly.GetPoint2dAt(i + 1);
                                switch (segmentType)
                                {
                                case SegmentType.Line:
                                    addAlignmentSegment(startLoc, endLoc);
                                    break;

                                case SegmentType.Arc:
                                    CircularArc2d    arc       = new CircularArc2d(startLoc, endLoc, alignmentPoly.GetBulgeAt(i), false);
                                    Interval         interval  = arc.GetInterval();
                                    PointOnCurve2d[] samplePts = arc.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.1);
                                    for (int n = 0; n < samplePts.Length - 1; n++)
                                    {
                                        addAlignmentSegment(samplePts[n].Point, samplePts[n + 1].Point);
                                    }
                                    break;
                                }
                            }


                            //проход по каждому отрезку трассы (диапазон отрезка - диапазон длины полилинии)
                            HashSet <HatchData> currentHatchData = new HashSet <HatchData>();
                            foreach (AlignmentSegment alignmentSegment in alignmentSegments)
                            {
                                if (eventQueue.Count == 0)
                                {
                                    break;                       //штриховки закончились
                                }
                                //Получить те штриховки, диапазон по X которых пересекается с диапазоном текущего отрезка
                                //(СКАНИРУЮЩАЯ ЛИНИЯ: события - начало, конец штриховки)
                                HashSet <HatchData> intervalHatchData = new HashSet <HatchData>(currentHatchData);//штриховки пришедшие из предыдущего участка остаются все

                                //Собрать все события до конца сегмента
                                //Если при проходе от начала до конца сегмента какая-то штриховка проходится полностью от начала до конца, то
                                //все ее контуры без изменений должны быть переданы для создания М-полигона!!! (для них обход графа не нужен!)
                                HashSet <HatchData> startedInsideInterval           = new HashSet <HatchData>();
                                List <HatchData>    hatchesCompletelyInsideInterval = new List <HatchData>();
                                while (eventQueue.Count > 0)
                                {
                                    HatchEvent nextEvent = eventQueue.FindMin();
                                    if (nextEvent.Position > alignmentSegment.End)
                                    {
                                        break;
                                    }
                                    else if (nextEvent.Start)
                                    {
                                        //добавить штриховку в текущий набор
                                        HatchData hd = eventQueue.DeleteMin().HatchData;
                                        currentHatchData.Add(hd);
                                        //добавлять в набор текущего интервла только в том случае,
                                        //если сканирующая линия еще не дошла до конца интервала
                                        if (nextEvent.Position < alignmentSegment.End &&
                                            !Utils.LengthIsEquals(nextEvent.Position, alignmentSegment.End))   //Допуск нужен
                                        {
                                            startedInsideInterval.Add(hd);
                                            intervalHatchData.Add(hd);
                                        }
                                    }
                                    else
                                    {
                                        //убрать штриховку из текущего набора
                                        HatchData hd = eventQueue.DeleteMin().HatchData;
                                        currentHatchData.Remove(hd);

                                        if (startedInsideInterval.Contains(hd))
                                        {
                                            hatchesCompletelyInsideInterval.Add(hd);
                                        }
                                    }
                                }

                                foreach (HatchData hd in hatchesCompletelyInsideInterval)
                                {
                                    HatchSegmentData hsd = new HatchSegmentData(hd);
                                    alignmentSegment.HatchSegmentData.Add(hsd);

                                    hsd.Polygons = hd.GetAllBoundaries();
                                }


                                intervalHatchData.ExceptWith(hatchesCompletelyInsideInterval);
                                foreach (HatchData hd in intervalHatchData)
                                {
                                    HatchSegmentData hsd = new HatchSegmentData(hd);
                                    alignmentSegment.HatchSegmentData.Add(hsd);
                                    //для каждой штриховки выполнить построение и обход графа сегмента штриховки
                                    HatchSegmentGraph graph = new HatchSegmentGraph(alignmentSegment.Start, alignmentSegment.End, hd, doc.Editor);

                                    //сохранить наборы полигонов для текущего диапазона
                                    hsd.Polygons = graph.Result;
                                }
                            }



                            //для каждого диапазона создать полученные полигоны в 3d
                            BlockTable       bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                            BlockTableRecord ms
                                = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                            BlockTableRecord btr = new BlockTableRecord();//Каждый профиль в отдельный блок
                            btr.Name = Guid.NewGuid().ToString();
                            ObjectId btrId = bt.Add(btr);
                            tr.AddNewlyCreatedDBObject(btr, true);

                            foreach (AlignmentSegment alignmentSegment in alignmentSegments)
                            {
                                List <Entity> flatObjs = new List <Entity>();

                                foreach (HatchSegmentData hsd in alignmentSegment.HatchSegmentData)
                                {
                                    //PlaneSurface
                                    hsd.GetNesting();
                                    Dictionary <Point2dCollection, List <Point2dCollection> > bwhs = hsd.GetBoundariesWithHoles();
                                    foreach (KeyValuePair <Point2dCollection, List <Point2dCollection> > bwh in bwhs)
                                    {
                                        //создать Region
                                        Region region = null;
                                        using (Polyline poly = new Polyline())
                                        {
                                            for (int i = 0; i < bwh.Key.Count; i++)
                                            {
                                                poly.AddVertexAt(i, bwh.Key[i], 0, 0, 0);
                                            }
                                            poly.Closed = true;
                                            DBObjectCollection coll = new DBObjectCollection();
                                            coll.Add(poly);
                                            try
                                            {
                                                DBObjectCollection regionColl = Region.CreateFromCurves(coll);
                                                foreach (DBObject dbo in regionColl)
                                                {
                                                    region = (Region)dbo;
                                                    break;
                                                }
                                            }
                                            catch { }
                                        }

                                        //из Region создать PlaneSurface
                                        if (region != null)
                                        {
                                            using (PlaneSurface planeSurface = new PlaneSurface())
                                            {
                                                planeSurface.CreateFromRegion(region);
                                                planeSurface.LayerId    = hsd.Hatch.LayerId;
                                                planeSurface.ColorIndex = 256;



                                                ObjectId planeSurfaceId = ms.AppendEntity(planeSurface);
                                                tr.AddNewlyCreatedDBObject(planeSurface, true);


                                                //вырезать отверстия в PlaneSurface

                                                foreach (Point2dCollection holePts2d in bwh.Value)
                                                {
                                                    if (holePts2d.Count < 3)
                                                    {
                                                        continue;
                                                    }

                                                    using (Polyline poly = new Polyline())
                                                    {
                                                        for (int i = 0; i < holePts2d.Count; i++)
                                                        {
                                                            poly.AddVertexAt(i, holePts2d[i], 0, 0, 0);
                                                        }
                                                        poly.Closed = true;

                                                        ObjectIdCollection trimPolyColl = new ObjectIdCollection();
                                                        trimPolyColl.Add(ms.AppendEntity(poly));
                                                        tr.AddNewlyCreatedDBObject(poly, true);

                                                        List <Point2d> ptsList  = new List <Point2d>(holePts2d.ToArray());
                                                        Point2d        pickPt2d = Utils.GetAnyPointInsidePoligon(ptsList,
                                                                                                                 Utils.DirectionIsClockwise(ptsList));

                                                        try
                                                        {
                                                            AcadDB.Surface.TrimSurface(planeSurfaceId, new ObjectIdCollection(), trimPolyColl,
                                                                                       new Vector3dCollection()
                                                            {
                                                                Vector3d.ZAxis
                                                            }, new Point3d(pickPt2d.X, pickPt2d.Y, 0),
                                                                                       -Vector3d.ZAxis, false, false);
                                                        }
                                                        catch /*(Exception ex)*/
                                                        {
                                                            //Вывод в командную строку
                                                            Utils.ErrorToCommandLine(doc.Editor,
                                                                                     "Ошибка при попытке вырезания отверстия в поверхности" /*, ex*/);
                                                        }

                                                        //Удалить все объекты, добавленные в чертеж!
                                                        poly.Erase();
                                                    }
                                                }


                                                flatObjs.Add((Entity)planeSurface.Clone());

                                                //Удалить все объекты, добавленные в чертеж!
                                                planeSurface.Erase();
                                            }
                                            region.Dispose();
                                        }
                                    }
                                }



                                foreach (Entity ent in flatObjs)
                                {
                                    ent.TransformBy(alignmentSegment.Transform);
                                    /*ms*/
                                    btr.AppendEntity(ent);
                                    tr.AddNewlyCreatedDBObject(ent, true);
                                    ent.Dispose();
                                }
                            }

                            BlockReference br = new BlockReference(Point3d.Origin, btrId);
                            ms.AppendEntity(br);
                            tr.AddNewlyCreatedDBObject(br, true);


                            if (selfintersectingLoops.Count > 0)
                            {
                                Utils.ErrorToCommandLine(doc.Editor,
                                                         "Отбраковано самопересекающихся контуров штриховок - " + selfintersectingLoops.Count + " (отмечены на профиле)");

                                ObjectId layerId = Utils.CreateLayerIfNotExists("САМОПЕРЕСЕКАЮЩИЙСЯ КОНТУР ШТРИХОВКИ", db, tr,
                                                                                color: Color.FromColorIndex(ColorMethod.ByAci, 1), lineWeight: LineWeight.LineWeight200);
                                Matrix2d returnTransform = transform.Inverse();
                                foreach (Point2dCollection pts in selfintersectingLoops)
                                {
                                    using (Polyline selfIntersectingPoly = new Polyline())
                                    {
                                        selfIntersectingPoly.LayerId    = layerId;
                                        selfIntersectingPoly.ColorIndex = 256;
                                        for (int i = 0; i < pts.Count; i++)
                                        {
                                            Point2d pt = pts[i].TransformBy(returnTransform);
                                            selfIntersectingPoly.AddVertexAt(i, pt, 0, 0, 0);
                                        }

                                        toHighlight.Add(ms.AppendEntity(selfIntersectingPoly));
                                        tr.AddNewlyCreatedDBObject(selfIntersectingPoly, true);

                                        //selfIntersectingPoly.Highlight();
                                    }
                                }
                            }


                            tr.Commit();
                        }
                    }
                    ps.Visible = false;

                    if (toHighlight.Count > 0)
                    {
                        using (Transaction tr = doc.Database.TransactionManager.StartTransaction())
                        {
                            foreach (ObjectId id in toHighlight)
                            {
                                Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                                ent.Highlight();
                            }
                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                GeologyConvertationCommand.ClosePalette(null, null);
                CommonException(ex, "Ошибка при создании 3d профиля геологии");
            }
        }
Example #11
0
 /// <summary>
 /// Sets the size of the viewport according to the provided extents.
 /// </summary>
 /// <param name="ext">The extents of the viewport on the page.</param>
 /// <param name="fac">Optional factor to provide padding.</param>
 public static void ResizeViewport(this Viewport vp, Extents2d ext, double fac = 1.0)
 {
     vp.Width       = (ext.MaxPoint.X - ext.MinPoint.X) * fac;
     vp.Height      = (ext.MaxPoint.Y - ext.MinPoint.Y) * fac;
     vp.CenterPoint = (Point2d.Origin + (ext.MaxPoint - ext.MinPoint) * 0.5).Pad();
 }
Example #12
0
            /// <summary>
            /// 设置打印信息
            /// </summary>
            /// <param name="layoutId">布局ID</param>
            /// <param name="plotArea">该布局中的一个区域</param>
            /// <param name="plotDevice">打印设备名</param>
            /// <param name="plotCanonicalMeida">标准打印介质名</param>
            /// <param name="plotStyle">打印样式</param>
            /// <param name="isSinglePage">是否只打印单页</param>
            /// <returns></returns>
      private static PlotInfo SetPlotInfo(Layout lo, Extents2d plotArea,string plotDevice, string plotCanonicalMeida, string plotStyle, bool isSinglePage)
        {
            PlotInfo pi = new PlotInfo();
            pi.Layout = lo.Id;

            //获取当前布局的打印信息
            PlotSettings ps = new PlotSettings(lo.ModelType);//是否模型空间
            ps.CopyFrom(lo);

            //着色打印选项,设置按线框进行打印
            ps.ShadePlot = PlotSettingsShadePlotType.Wireframe;

            //获取当前打印设置校验器
            PlotSettingsValidator psv = PlotSettingsValidator.Current;

            #region 以下这些设置请不要改变顺序!!!
            //以下2句顺序不能换!
            psv.SetPlotWindowArea(ps, plotArea);//设置打印区域            
            psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);//设置为窗口打印模式

            //设置布满图纸打印
            psv.SetUseStandardScale(ps, true);//需要?
            psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);//布满图纸

            //设置居中打印
            psv.SetPlotCentered(ps, true);

            //设置打印样式
            try
            {
                psv.SetCurrentStyleSheet(ps, plotStyle);//设置打印样式(笔宽等)(为什么有时会出错?PS:不能与原样式形同?!!!)
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
               // MessageBox.Show(string.Format("{0}\n当前打印样式:{1}\n设置打印样式:{2}", e.Message, ps.CurrentStyleSheet, plotStyle), "设置打印样式出错");
            }

            //配置打印机和打印介质
            psv.SetPlotConfigurationName(ps, plotDevice, plotCanonicalMeida);
            psv.RefreshLists(ps);

            //设置打印单位
            try
            {
                psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//(为什么有时会出错?)            
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                //MessageBox.Show(string.Format("{0}\n当前尺寸单位:{1}\n设置单位:{2}", e.Message, ps.PlotPaperUnits, PlotPaperUnit.Millimeters), "设置尺寸单位出错");
            }

            //设置旋转角度(打印到同一文档时必须设置为同一旋转角)
            if (isSinglePage)
            {
                if ((plotArea.MaxPoint.X - plotArea.MinPoint.X) > (plotArea.MaxPoint.Y - plotArea.MinPoint.Y))
                {
                    if (ps.PlotPaperSize.X > ps.PlotPaperSize.Y)
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees000);
                    }
                    else
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                    }
                }
                else
                {
                    if (ps.PlotPaperSize.X > ps.PlotPaperSize.Y)
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                    }
                    else
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees000);
                    }
                }
            }
            else
            {
                //多页打印必须设置为统一旋转角度(否则打印会出错,出错信息:eValidePlotInfo!特别注意!!!)
                psv.SetPlotRotation(ps, PlotRotation.Degrees000);
            }
            #endregion

            pi.OverrideSettings = ps;//将PlotSetting与PlotInfo关联

            PlotInfoValidator piv = new PlotInfoValidator();
            piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
            piv.Validate(pi);//激活打印设置

            ps.Dispose();

            return pi;
        }