예제 #1
0
        /// <summary>
        /// 预览按钮处理。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Preview(object sender, RoutedEventArgs e)
        {
            try
            {
                // 生成边坡实体集合,按实体边界获取截取窗口。
                previewEnts = MakeBianpo(view);
                var extents = new AcDb.Extents3d();
                foreach (var ent in previewEnts.OfType <AcDb.Curve>())
                {
                    extents.AddExtents(ent.GeometricExtents);
                }
                previewExtents = extents;

                // 生成Bitmap,显示到界面的图片上。
                using (var bitmap = GraphicHelper.Snapshort(previewEnts,
                                                            kPreviewImageWidth, kPreviewImageHeight,
                                                            previewExtents.MinPoint, previewExtents.MaxPoint))
                {
                    ShowImage(bitmap);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }
예제 #2
0
파일: CADOperator.cs 프로젝트: 15831944/RLA
        public Extents3d GetCorner(string baseword, string targetword)
        {
            Editor              ed       = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Point3d             basept   = GetPoint(baseword);
            Point3d             targetpt = new Point3d();
            PromptCornerOptions options  = new PromptCornerOptions(targetword, basept);
            PromptPointResult   i        = ed.GetCorner(options);

            if (i.Status == PromptStatus.OK)
            {
                targetpt = i.Value;
            }
            Autodesk.AutoCAD.DatabaseServices.Extents3d ext = new Autodesk.AutoCAD.DatabaseServices.Extents3d();
            ext.AddPoint(targetpt);
            ext.AddPoint(basept);

            return(ext);
        }
예제 #3
0
        // Boxes
        public Box BoxToSpeckle(AcadDB.Extents3d extents, bool OrientToWorldXY = false)
        {
            try
            {
                Box box = null;

                // get dimension intervals
                var xSize = new Interval(extents.MinPoint.X, extents.MaxPoint.X);
                var ySize = new Interval(extents.MinPoint.Y, extents.MaxPoint.Y);
                var zSize = new Interval(extents.MinPoint.Z, extents.MaxPoint.Z);

                // get box size info
                double area   = 2 * ((xSize.Length * ySize.Length) + (xSize.Length * zSize.Length) + (ySize.Length * zSize.Length));
                double volume = xSize.Length * ySize.Length * zSize.Length;

                if (OrientToWorldXY)
                {
                    var origin = new Point3d(0, 0, 0);
                    var normal = new Vector3d(0, 0, 1);
                    var plane  = PlaneToSpeckle(new Autodesk.AutoCAD.Geometry.Plane(origin, normal));
                    box = new Box(plane, xSize, ySize, zSize, ModelUnits)
                    {
                        area = area, volume = volume
                    };
                }
                else
                {
                    // get base plane
                    var corner = new Point3d(extents.MaxPoint.X, extents.MaxPoint.Y, extents.MinPoint.Z);
                    var origin = new Point3d((corner.X + extents.MinPoint.X) / 2, (corner.Y + extents.MinPoint.Y) / 2, (corner.Z + extents.MinPoint.Z) / 2);
                    var plane  = PlaneToSpeckle(new Autodesk.AutoCAD.Geometry.Plane(extents.MinPoint, origin, corner));
                    box = new Box(plane, xSize, ySize, zSize, ModelUnits)
                    {
                        area = area, volume = volume
                    };
                }

                return(box);
            }
            catch
            {
                return(null);
            }
        }
예제 #4
0
        public void test() // This method can have any name
        {
            /*
             * "AEC_WALL"
             * "AEC_WINDOW"
             * "AEC_DOOR"
             */
            ObjectIdCollection ids = VladUtils.qacSSet.qF_GetObjIdByEntStrAndLayerStr("AEC_*", "", false);
            // Put your command code here
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = Application.DocumentManager.MdiActiveDocument.Database;
            //Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            //Transaction tr = tm.StartTransaction();
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ///ccccc
            double wallHeightToSet         = 120;
            double windowsLowerHeightToSet = 10;
            double windowsUpperHeightToSet = 40;
            double precision = 0.0000;
            ///hhh
            double doorHeightToSet   = 60;
            double windowHeightToSet = windowsUpperHeightToSet - windowsLowerHeightToSet;
            ///ddd
            ///dddd
            //ddddd
            string
            //walls
                keyWallsWrongHeights = "AEC_WALLS_WRONG_HEIGHTS",
                keyWallsOutBB        = "AEC_WALLS_OUT_BB",
            //windows
                keyWindowsWrongHeights = "AEC_WINDOWS_WRONG_HEIGHTS",
                keyWindowsOutBB        = "AEC_WINDOWS_OUT_BB",
                keyWindowsHigherWalls  = "AEC_WINDOWS_HIGHER_WALLS",
                keyWindowsNotBottom    = "AEC_WINDOWS_NOT_BOTTOM",
                keyWindowsNotTop       = "AEC_WINDOWS_NOT_TOP",
            //door
                keyDoorsWrongHeights = "AEC_DOOR_WRONG_HEIGHTS",
                keyDoorsOutBB        = "AEC_DOORS_WRONG_HEIGHTS",
                keyDoorsHigherWalls  = "AEC_DOORS_HIGHER_WALLS",
            //rest of AEC
                keyRestOfAecOutBB = "AEC_TEST_OF_AEC";



            Dictionary <string, List <string> > AecObjectsOutBB = new Dictionary <string, List <string> >();

            //walls
            AecObjectsOutBB.Add(keyWallsWrongHeights, new List <string>());
            AecObjectsOutBB.Add(keyWallsOutBB, new List <string>());
            //windows
            AecObjectsOutBB.Add(keyWindowsWrongHeights, new List <string>());
            AecObjectsOutBB.Add(keyWindowsOutBB, new List <string>());
            AecObjectsOutBB.Add(keyWindowsHigherWalls, new List <string>());
            AecObjectsOutBB.Add(keyWindowsNotBottom, new List <string>());
            AecObjectsOutBB.Add(keyWindowsNotTop, new List <string>());
            //doors
            AecObjectsOutBB.Add(keyDoorsWrongHeights, new List <string>());
            AecObjectsOutBB.Add(keyDoorsOutBB, new List <string>());
            AecObjectsOutBB.Add(keyDoorsHigherWalls, new List <string>());
            //rest
            AecObjectsOutBB.Add(keyRestOfAecOutBB, new List <string>());



            Boolean updateWalls   = true;
            Boolean updateWindows = true;
            Boolean updateDoors   = true;

            Boolean commit = false;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                try
                {
                    using (DocumentLock acLckDoc = doc.LockDocument())
                    {
                        if (doc != null)
                        {
                            for (int i = 0; i < ids.Count; i++)
                            {
                                /// >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>> WALLS >>>
                                /// walls rules
                                /// all together:
                                /// higher=>to default
                                /// lower=>to default
                                /// manually
                                /// set question?????
                                if (ids[i].ObjectClass.DxfName == "AEC_WALL")
                                {
                                    Autodesk.Aec.Arch.DatabaseServices.Wall wall = tr.GetObject(ids[i], OpenMode.ForRead) as Autodesk.Aec.Arch.DatabaseServices.Wall;
                                    double wallHeight = wall.BaseHeight;
                                    if (!VladMathTools.qNMath.IsSameNumbers(wallHeight, wallHeightToSet, precision))
                                    {
                                        AecObjectsOutBB[keyWallsWrongHeights].Add(ids[i].Handle.ToString());

                                        if (updateWalls)
                                        {
                                            wall.UpgradeOpen();
                                            wall.BaseHeight = wallHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }
                                    else if (wall.GeometricExtents != null)
                                    {
                                        if (wall.GeometricExtents.MinPoint.Z != 0 || wall.GeometricExtents.MaxPoint.Z > wallHeightToSet)
                                        {
                                            AecObjectsOutBB[keyWallsOutBB].Add(ids[i].Handle.ToString());
                                        }
                                    }
                                }


                                //windows

                                /*
                                 * AecObjectsOutBB.Add(keyWindowsWrongHeights, new List<string>());
                                 * //ecObjectsOutBB.Add(keyWindowsOutBB, new List<string>());
                                 * //AecObjectsOutBB.Add(keyWindowsHigherWalls, new List<string>());
                                 * AecObjectsOutBB.Add(keyWindowsNotBottom, new List<string>());
                                 * AecObjectsOutBB.Add(keyWindowsNotTop, new List<string>());
                                 *
                                 */


                                /// >>> WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>  WINDOWS >>>
                                /// windows rules
                                /// all together:
                                /// height => to default
                                /// sill => to default
                                /// manually
                                /// set question?????
                                else if (ids[i].ObjectClass.DxfName == "AEC_WINDOW")
                                {
                                    Autodesk.Aec.Arch.DatabaseServices.Window window = tr.GetObject(ids[i], OpenMode.ForRead) as Autodesk.Aec.Arch.DatabaseServices.Window;
                                    double
                                        height = window.Height,
                                        bottom = window.StartPoint.Z,
                                        top    = height + bottom;



                                    if (window.GeometricExtents != null)
                                    {
                                        if (window.GeometricExtents.MinPoint.Z != 0 || window.GeometricExtents.MaxPoint.Z > wallHeightToSet)
                                        {
                                            AecObjectsOutBB[keyWindowsOutBB].Add(ids[i].Handle.ToString());
                                        }
                                    }
                                    if (window.Height >= wallHeightToSet)
                                    {
                                        AecObjectsOutBB[keyWindowsHigherWalls].Add(ids[i].Handle.ToString());

                                        if (updateWindows)
                                        {
                                            window.UpgradeOpen();
                                            //    window.Height = windowHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }


                                    /*
                                     * double wallHeightToSet = 120;
                                     * double windowsLowerHeightToSet = 30;ddd
                                     * double windowsUpperHeightToSet = 60;
                                     * double precision = 0.0000;
                                     *
                                     * double doorHeightToSet = 60;
                                     * double windowHeightToSet = windowsUpperHeightToSet - windowsLowerHeightToSet;
                                     */



                                    if (!qNMath.IsSameNumbers(height, wallHeightToSet, precision))
                                    {
                                        AecObjectsOutBB[keyWindowsWrongHeights].Add(ids[i].Handle.ToString());

                                        if (updateWindows)
                                        {
                                            window.UpgradeOpen();
                                            //  window.Height = windowHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }


                                    if (!qNMath.IsSameNumbers(bottom, windowsLowerHeightToSet, precision))
                                    {
                                        AecObjectsOutBB[keyWindowsNotBottom].Add(ids[i].Handle.ToString());

                                        if (updateWindows)
                                        {
                                            window.UpgradeOpen();
                                            //   window.Height = windowHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }



                                    if (!qNMath.IsSameNumbers(top, windowsUpperHeightToSet, precision))
                                    {
                                        AecObjectsOutBB[keyWindowsNotTop].Add(ids[i].Handle.ToString());

                                        if (updateWindows)
                                        {
                                            window.UpgradeOpen();
                                            //  window.Height = windowHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }
                                    window.UpgradeOpen();

                                    if (!commit)
                                    {
                                        commit = true;
                                    }


                                    //     window.Height = windowHeightToSet;
                                    //Curve3d curve = window.GetGeCurve();

                                    Autodesk.AutoCAD.DatabaseServices.Extents3d bbb = window.GeometricExtents;

                                    window.Height = 50;
                                    Point3d Location = new Point3d(window.Location.X, window.Location.Y, 20);
                                    window.Location = Location;

                                    /*
                                     * BoundBlock3d bb = new BoundBlock3d();
                                     * Point3d MinPoint = new Point3d(bbb.MinPoint.X, bbb.MinPoint.Y, 20);
                                     * Point3d MaxPoint = new Point3d(bbb.MaxPoint.X, bbb.MaxPoint.Y, 20 + 50);
                                     *
                                     *
                                     *
                                     * bb.Set(MinPoint, MaxPoint);
                                     *
                                     *
                                     * window.SetLocalExtents(bb, 3);
                                     */

                                    //  window.SetLocalExtents
                                    int jjj = 1;

                                    //    window.SetFromGeCurve(new  = new Point3d(window.StartPoint.X, window.StartPoint.Y,20);
                                    //window.EndPoint = new Point3d(window.EndPoint.X, window.EndPoint.Y, 20);



                                    //else if (Height >= WallHeightToSet)
                                    //{
                                    //    AecObjectsOutBB[keyWindowsHigherWalls].Add(ids[i].Handle.ToString());

                                    //    if (updateWindows)
                                    //    {
                                    //        window.UpgradeOpen();
                                    //        window.Height = windowHeight;
                                    //        if (!commit) commit = true;
                                    //    }
                                    //}
                                }

                                /// >>> DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>  DOORS >>>
                                else if (ids[i].ObjectClass.DxfName == "AEC_DOOR")
                                {
                                    Autodesk.Aec.Arch.DatabaseServices.Door door = tr.GetObject(ids[i], OpenMode.ForRead) as Autodesk.Aec.Arch.DatabaseServices.Door;
                                    double Height = door.Height;
                                    if (Height >= wallHeightToSet)
                                    {
                                        AecObjectsOutBB["AEC_DOOR_WRONG_HEIGHTS"].Add(ids[i].Handle.ToString());

                                        if (updateDoors)
                                        {
                                            door.UpgradeOpen();
                                            door.Height = doorHeightToSet;
                                            if (!commit)
                                            {
                                                commit = true;
                                            }
                                        }
                                    }
                                    else if (door.GeometricExtents != null)
                                    {
                                        if (door.GeometricExtents.MinPoint.Z != 0 || door.GeometricExtents.MaxPoint.Z > wallHeightToSet)
                                        {
                                            AecObjectsOutBB["AEC_DOOR_OUT_BB"].Add(ids[i].Handle.ToString());
                                        }
                                    }
                                }

                                ////// >>> REST OF AEC >>>  REST OF AEC >>>  REST OF AEC >>>  REST OF AEC >>>  REST OF AEC >>>  REST OF AEC >>>  REST
                                //else if (ids[i].ObjectClass.DxfName.StartsWith ("AEC_"))
                                if (ids[i].ObjectClass.DxfName.StartsWith("AEC_"))
                                {
                                    Entity aecEntiy = tr.GetObject(ids[i], OpenMode.ForRead) as Entity;

                                    if (aecEntiy.GeometricExtents != null)
                                    {
                                        if (aecEntiy.GeometricExtents.MinPoint.Z < 0 || aecEntiy.GeometricExtents.MinPoint.Z > wallHeightToSet)
                                        {
                                            AecObjectsOutBB[keyRestOfAecOutBB].Add(ids[i].Handle.ToString());
                                        }
                                    }
                                }
                            }


                            if (commit)
                            {
                                tr.Commit();
                            }

                            ed = doc.Editor;
                            ed.WriteMessage(ids.Count.ToString());
                        }
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {
                    tr.Abort();
                    ed.WriteMessage("\n" + e.Message + "\n");
                }
            }
        }
예제 #5
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotOnePaper(Database db, Document doc, BlockReference br, String pcsFileName,
                                        String mediaName, String outputFileName)
        {
            ;

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }



            Ed.Editor ed = doc.Editor;

            try
            {
                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Extents3d extends = br.GeometryExtentsBestFit();
                        Point3d      pmin    = extends.MinPoint;
                        Point3d      pmax    = extends.MaxPoint;



                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo PltInfo = new Pt.PlotInfo())
                        {
                            PltInfo.Layout = model.LayoutId;

                            using (Db.PlotSettings PltSet = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                PltSet.CopyFrom(layout);

                                Db.PlotSettingsValidator PltSetVald = Db.PlotSettingsValidator
                                                                      .Current;


                                Db.Extents2d extents = new Db.Extents2d(
                                    pmin.X * (1 - 0.0001),
                                    pmin.Y * (1 + 0.001),
                                    pmax.X,
                                    pmax.Y
                                    );

                                Log4NetHelper.WriteInfoLog("左上角坐标:" + pmin.X + "," + pmin.Y + "\n");
                                Log4NetHelper.WriteInfoLog("右下角角坐标:" + pmax.X + "," + pmax.Y + "\n");



                                PltSetVald.SetZoomToPaperOnUpdate(PltSet, true);

                                PltSetVald.SetPlotWindowArea(PltSet, extents);
                                PltSetVald.SetPlotType(PltSet, Db.PlotType.Window);
                                PltSetVald.SetUseStandardScale(PltSet, true);
                                PltSetVald.SetStdScaleType(PltSet, Db.StdScaleType.ScaleToFit);
                                PltSetVald.SetPlotCentered(PltSet, true);
                                PltSetVald.SetPlotRotation(PltSet, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                PltSetVald.SetPlotConfigurationName(PltSet, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                PltInfo.OverrideSettings = PltSet;
                                Pt.PlotInfoValidator PltInfoVald = new Pt.PlotInfoValidator();
                                PltInfoVald.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                PltInfoVald.Validate(PltInfo);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(PltInfo, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, PltInfo, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                //  Hs.WorkingDatabase = previewDb;
            }
        }
예제 #6
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotRegion(Db.ObjectId regionId, String pcsFileName,
                                      String mediaName, String outputFileName)
        {
            if (regionId.IsNull)
            {
                throw new ArgumentException("regionId.IsNull == true");
            }
            if (!regionId.IsValid)
            {
                throw new ArgumentException("regionId.IsValid == false");
            }

            if (regionId.ObjectClass.Name != "AcDbRegion")
            {
                throw new ArgumentException("regionId.ObjectClass.Name != AcDbRegion");
            }

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }

            Db.Database previewDb = Hs.WorkingDatabase;
            Db.Database db        = null;
            Ap.Document doc       = cad.DocumentManager.MdiActiveDocument;
            if (doc == null || doc.IsDisposed)
            {
                return;
            }

            Ed.Editor ed = doc.Editor;
            try
            {
                if (regionId.Database != null && !regionId.Database.IsDisposed)
                {
                    Hs.WorkingDatabase = regionId.Database;
                    db = regionId.Database;
                }
                else
                {
                    db = doc.Database;
                }

                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Region region = tr.GetObject(regionId,
                                                        Db.OpenMode.ForRead) as Db.Region;

                        Db.Extents3d        extends = region.GeometricExtents;
                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo pi = new Pt.PlotInfo())
                        {
                            pi.Layout = model.LayoutId;

                            using (Db.PlotSettings ps = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                ps.CopyFrom(layout);

                                Db.PlotSettingsValidator psv = Db.PlotSettingsValidator
                                                               .Current;

                                Gm.Point2d bottomLeft = Gm.Point2d.Origin;
                                Gm.Point2d topRight   = Gm.Point2d.Origin;

                                region.GetVisualBoundary(0.1, ref bottomLeft,
                                                         ref topRight);

                                Gm.Point3d bottomLeft_3d = new Gm.Point3d(bottomLeft.X,
                                                                          bottomLeft.Y, 0);
                                Gm.Point3d topRight_3d = new Gm.Point3d(topRight.X, topRight.Y,
                                                                        0);

                                Db.ResultBuffer rbFrom = new Db.ResultBuffer(new Db.TypedValue(
                                                                                 5003, 1));
                                Db.ResultBuffer rbTo = new Db.ResultBuffer(new Db.TypedValue(
                                                                               5003, 2));

                                double[] firres = new double[] { 0, 0, 0 };
                                double[] secres = new double[] { 0, 0, 0 };

                                acedTrans(bottomLeft_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, firres);
                                acedTrans(topRight_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, secres);

                                Db.Extents2d extents = new Db.Extents2d(
                                    firres[0],
                                    firres[1],
                                    secres[0],
                                    secres[1]
                                    );

                                psv.SetZoomToPaperOnUpdate(ps, true);

                                psv.SetPlotWindowArea(ps, extents);
                                psv.SetPlotType(ps, Db.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, Db.StdScaleType.ScaleToFit);
                                psv.SetPlotCentered(ps, true);
                                psv.SetPlotRotation(ps, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                psv.SetPlotConfigurationName(ps, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                pi.OverrideSettings = ps;
                                Pt.PlotInfoValidator piv = new Pt.PlotInfoValidator();
                                piv.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                piv.Validate(pi);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(pi, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, pi, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                Hs.WorkingDatabase = previewDb;
            }
        }