/// <summary>
        /// Создание коллекции PlotSettingsInfo из пользовательских форматов
        /// в файле DWG to PDF.pc3
        /// Также в коллекцию будут включены форматы, начинающиеся с "ISO_A" - это поведение
        /// подлежит изменению
        /// </summary>
        /// <returns>Коллекция PlotSettingsInfo</returns>
        public static IEnumerable <PlotSettingsInfo> CreatePlotSettingsInfos()
        {
            string   PLOTTER_NAME = "DWG To PDF.pc3";
            Database db           = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                PlotSettings          ps  = new PlotSettings(false);
                psv.RefreshLists(ps);
                psv.SetPlotConfigurationName(ps, PLOTTER_NAME, null);
                // Получаем список CanonicalMediaNames плоттера
                StringCollection canonicalMediaNames = psv.GetCanonicalMediaNameList(ps);

                string plotStyle = "acad.ctb";
                System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"[\<>/?"":;*|,=`]");

                for (int nameIndex = 0; nameIndex < canonicalMediaNames.Count; nameIndex++)
                {
                    // Работаем только с пользовательскими форматами
                    if (canonicalMediaNames[nameIndex].Contains("UserDefinedMetric") ||
                        canonicalMediaNames[nameIndex].StartsWith("ISO_A"))
                    {
                        psv.SetPlotConfigurationName(ps, PLOTTER_NAME, canonicalMediaNames[nameIndex]);

                        psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Layout);
                        psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);

                        psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);
                        psv.SetUseStandardScale(ps, true);

                        psv.SetCurrentStyleSheet(ps, plotStyle);

                        if (canonicalMediaNames[nameIndex].StartsWith("ISO_A0"))
                        {
                            psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                        }
                        else
                        {
                            psv.SetPlotRotation(ps, PlotRotation.Degrees000);
                        }

                        string plotSettingsName = re.Replace(psv.GetLocaleMediaName(ps, nameIndex), "");
                        if (string.IsNullOrEmpty(plotSettingsName))
                        {
                            plotSettingsName = canonicalMediaNames[nameIndex];
                        }
                        ps.PlotSettingsName = plotSettingsName;

                        PlotSettings newPS = new PlotSettings(false);
                        newPS.CopyFrom(ps);
                        yield return(new PlotSettingsInfo(newPS));
                    }
                }
            }
        }
Beispiel #2
0
        public static void SetPageSize(Layout layout)
        {
            using (DocumentLock documentLock = Document.LockDocument())
            {
                using (Transaction setpageTransaction = Document.Database.TransactionManager.StartTransaction())
                {
                    using (PlotSettings plotSettings = new PlotSettings(layout.ModelType))
                    {
                        using (PlotSettingsValidator plotSettingsValidator = PlotSettingsValidator.Current)
                        {
                            layout = (Layout)setpageTransaction.GetObject(layout.ObjectId, OpenMode.ForWrite);

                            plotSettingsValidator.SetZoomToPaperOnUpdate(plotSettings, true);
                            plotSettingsValidator.SetPlotPaperUnits(plotSettings, PlotPaperUnit.Inches);
                        }
                    }
                }
            }
        }
Beispiel #3
0
        private void comboBoxMMInches_SelectedIndexChanged(object sender, EventArgs e)
        {
            String unitsStr = comboBoxMMInches.SelectedItem.ToString();

            PlotPaperUnit plotPaperUnits = PlotPaperUnit.Pixels;

            if (unitsStr == "mm")
            {
                plotPaperUnits = PlotPaperUnit.Millimeters;
            }
            else if (unitsStr == "inches")
            {
                plotPaperUnits = PlotPaperUnit.Inches;
            }

            PlotPaperUnit prevUnits = m_plotStg.PlotPaperUnits;

            m_plotSettingVal.SetPlotPaperUnits(m_plotStg, plotPaperUnits);
            unitsConverted(prevUnits, plotPaperUnits);

            FillScaleValues(false);
            FillPlotOffset();
        }
        public static void SetPageSize(this Layout curlay, double width, double height, PlotPaperUnit ppu)
        {
            Document      doc    = Application.DocumentManager.MdiActiveDocument;
            Database      db     = doc.Database;
            LayoutManager laymgr = LayoutManager.Current;

            using (DocumentLock dl = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    using (PlotSettings pltset = new PlotSettings(curlay.ModelType))
                    {
                        pltset.CopyFrom(curlay);
                        PlotSettingsValidator psv = PlotSettingsValidator.Current;
                        Layout layout             = new Layout();

                        try
                        {
                            if (curlay.ObjectId != null)
                            {
                                layout = tr.GetObject(curlay.ObjectId, OpenMode.ForWrite) as Layout;
                            }
                        }

                        catch
                        {
                        }

                        #region Paper Types
                        try
                        {
                            if (!ppu.Equals(PlotPaperUnit.Inches))
                            {
                                psv.SetPlotPaperUnits(pltset, PlotPaperUnit.Inches);
                            }

                            if ((width == 11.00 && height == 17.00) || (width == 17.00 && height == 11.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ANSI_full_bleed_B_(11.00_x_17.00_Inches)");
                            }

                            if ((width == 18.00 && height == 24.00) || (width == 24.00 && height == 18.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_B_(18.00_x_24.00_Inches)");
                            }

                            else if ((width == 17.00 && height == 22.00) || (width == 22.00 && height == 17.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_C_(17.00_x_22.00_Inches)");
                            }

                            else if ((width == 24.00 && height == 36.00) || (width == 36.00 && height == 24.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_D_(24.00_x_36.00_Inches)");
                            }

                            else if ((width == 36.00 && height == 48.00) || (width == 48.00 && height == 36.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_E_(36.00_x_48.00_Inches)");
                            }

                            else if ((width == 30.00 && height == 42.00) || (width == 42.00 && height == 30.00))
                            {
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_E1_(30.00_x_42.00_Inches)");
                            }

                            else
                            {
                                doc.Editor.WriteMessage("\n The drawing sizes were invalid, default setting will be used");
                                psv.SetPlotConfigurationName(pltset,
                                                             "DWG To PDF.pc3",
                                                             "ARCH_full_bleed_E_(36.00_x_48.00_Inches)");
                            }
                        }

                        catch
                        {
                            doc.Editor.WriteMessage("\n The drawing sizes were invalid, default setting will be used");
                            psv.SetPlotConfigurationName(pltset,
                                                         "DWG To PDF.pc3",
                                                         "ARCH_full_bleed_E_(36.00_x_48.00_Inches)");
                        }
                        #endregion

                        psv.SetZoomToPaperOnUpdate(pltset, true);

                        layout.UpgradeOpen();
                        layout.CopyFrom(pltset);

                        doc.Editor.WriteMessage("\n  " + "\nNew device name: " + layout.PlotConfigurationName);

                        tr.Commit();
                    }
                }
            }
        }
Beispiel #5
0
        static public void PublishViews2MultiSheet()
        {
            pwdWindow = new PasswordWindow();
            pwdWindow.ShowDialog();
            Document         doc         = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database         db          = doc.Database;
            Editor           ed          = doc.Editor;
            StringCollection viewsToPlot = new StringCollection();

            viewsToPlot.Add("Test1");
            viewsToPlot.Add("Test2");
            using (Transaction Tx = db.TransactionManager.StartTransaction())
            {
                ObjectId layoutId = LayoutManager.Current.GetLayoutId(LayoutManager.Current.CurrentLayout);
                Layout   layout   = Tx.GetObject(layoutId, OpenMode.ForWrite) as Layout;
                foreach (String viewName in viewsToPlot)
                {
                    PlotSettings plotSettings = new PlotSettings(layout.ModelType);
                    plotSettings.CopyFrom(layout);
                    PlotSettingsValidator psv = PlotSettingsValidator.Current;
                    psv.SetPlotConfigurationName(plotSettings, "DWF6 ePlot.pc3", "ANSI_A_(8.50_x_11.00_Inches)");
                    psv.RefreshLists(plotSettings);
                    psv.SetPlotViewName(plotSettings, viewName);
                    psv.SetPlotType(plotSettings, Autodesk.AutoCAD.DatabaseServices.PlotType.View);
                    psv.SetUseStandardScale(plotSettings, true);
                    psv.SetStdScaleType(plotSettings, StdScaleType.ScaleToFit);
                    psv.SetPlotCentered(plotSettings, true);
                    psv.SetPlotRotation(plotSettings, PlotRotation.Degrees000);
                    psv.SetPlotPaperUnits(plotSettings, PlotPaperUnit.Inches);
                    plotSettings.PlotSettingsName = String.Format("{0}{1}", viewName, "PS");
                    plotSettings.PrintLineweights = true;
                    plotSettings.AddToPlotSettingsDictionary(db);
                    Tx.AddNewlyCreatedDBObject(plotSettings, true);
                    psv.RefreshLists(plotSettings);
                    layout.CopyFrom(plotSettings);
                }
                Tx.Commit();
            }
            short bgPlot = (short)Autodesk.AutoCAD.ApplicationServices.Core.Application.GetSystemVariable("BACKGROUNDPLOT");

            Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
            string dwgFileName = Autodesk.AutoCAD.ApplicationServices.Core.Application.GetSystemVariable("DWGNAME") as string;
            string dwgPath     = Autodesk.AutoCAD.ApplicationServices.Core.Application.GetSystemVariable("DWGPREFIX") as string;

            using (Transaction Tx = db.TransactionManager.StartTransaction())
            {
                DsdEntryCollection collection     = new DsdEntryCollection();
                ObjectId           activeLayoutId = LayoutManager.Current.GetLayoutId(LayoutManager.Current.CurrentLayout);
                foreach (String viewName in viewsToPlot)
                {
                    Layout   layout = Tx.GetObject(activeLayoutId, OpenMode.ForRead) as Layout;
                    DsdEntry entry  = new DsdEntry();
                    entry.DwgName      = dwgPath + dwgFileName;
                    entry.Layout       = layout.LayoutName;
                    entry.Title        = viewName;
                    entry.NpsSourceDwg = entry.DwgName;
                    entry.Nps          = String.Format("{0}{1}", viewName, "PS");
                    collection.Add(entry);
                }
                dwgFileName = dwgFileName.Substring(0, dwgFileName.Length - 4);
                DsdData dsdData = new DsdData();
                dsdData.SheetType       = SheetType.MultiDwf;
                dsdData.ProjectPath     = dwgPath;
                dsdData.DestinationName = dsdData.ProjectPath + dwgFileName + ".dwf";
                /*Get password from user*/
                dsdData.Password = pwdWindow.passwordBox.Password;
                if (System.IO.File.Exists(dsdData.DestinationName))
                {
                    System.IO.File.Delete(dsdData.DestinationName);
                }
                dsdData.SetDsdEntryCollection(collection);

                /*DsdFile */
                string dsdFile = dsdData.ProjectPath + dwgFileName + ".dsd";
                dsdData.WriteDsd(dsdFile);
                System.IO.StreamReader sr = new System.IO.StreamReader(dsdFile);
                string str = sr.ReadToEnd();
                sr.Close();
                str = str.Replace("PromptForDwfName=TRUE",
                                  "PromptForDwfName=FALSE");
                /*Prompts User to Enter Password and Reconfirms*/
                //str = str.Replace("PromptForPwd=FALSE",
                //                   "PromptForPwd=TRUE");
                //str = str.Replace("PwdProtectPublishedDWF=FALSE",
                //                   "PwdProtectPublishedDWF=TRUE");
                int           occ        = 0;
                int           index      = str.IndexOf("Setup=");
                int           startIndex = 0;
                StringBuilder dsdText    = new StringBuilder();
                while (index != -1)
                {
                    String str1 = str.Substring(startIndex, index + 6 - startIndex);
                    dsdText.Append(str1);
                    dsdText.Append(String.Format("{0}{1}", viewsToPlot[occ], "PS"));
                    startIndex = index + 6;
                    index      = str.IndexOf("Setup=", index + 6);
                    if (index == -1)
                    {
                        dsdText.Append(str.Substring(startIndex, str.Length - startIndex));
                    }
                    occ++;
                }
                System.IO.StreamWriter sw = new System.IO.StreamWriter(dsdFile);
                sw.Write(dsdText.ToString());
                sw.Close();
                dsdData.ReadDsd(dsdFile);
                System.IO.File.Delete(dsdFile);
                PlotConfig plotConfig = PlotConfigManager.SetCurrentConfig("DWF6 ePlot.pc3");
                Publisher  publisher  = Autodesk.AutoCAD.ApplicationServices.Core.Application.Publisher;
                publisher.PublishExecute(dsdData, plotConfig);
                Tx.Commit();
            }
            Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);
        }
Beispiel #6
0
        // overload no scale factor or set the view - just make the layout
        public void LayoutAndViewport(Database db, string layoutName, out ObjectId rvpid, string deviceName, string mediaName, out ObjectId id)
        {
            // set default values
            rvpid = new ObjectId();
            bool          flagVp        = false; // flag to create a new floating view port
            double        viewSize      = (double)Application.GetSystemVariable("VIEWSIZE");
            double        height        = viewSize;
            double        width         = viewSize;
            Point2d       loCenter      = new Point2d(); // layout center point
            Point2d       vpLowerCorner = new Point2d();
            Point2d       vpUpperCorner = new Point2d();
            Document      doc           = Application.DocumentManager.MdiActiveDocument;
            LayoutManager lm            = LayoutManager.Current;

            id = lm.CreateLayout(layoutName);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Layout lo = tr.GetObject(id, OpenMode.ForWrite, false) as Layout;
                if (lo != null)
                {
                    lm.CurrentLayout = lo.LayoutName; // make it current!

                    #region do some plotting settings here for the paper size...
                    ObjectId loid = lm.GetLayoutId(lo.LayoutName);

                    PlotInfo pi = new PlotInfo();
                    pi.Layout = loid;

                    PlotSettings          ps  = new PlotSettings(false);
                    PlotSettingsValidator psv = PlotSettingsValidator.Current;

                    psv.RefreshLists(ps);
                    psv.SetPlotConfigurationName(ps, deviceName, mediaName);
                    psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Layout);
                    psv.SetPlotPaperUnits(ps, PlotPaperUnit.Inches);
                    psv.SetUseStandardScale(ps, true);
                    psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); // use this as default

                    pi.OverrideSettings = ps;

                    PlotInfoValidator piv = new PlotInfoValidator();
                    piv.Validate(pi);

                    lo.CopyFrom(ps);

                    PlotConfig pc = PlotConfigManager.CurrentConfig;
                    // returns data in millimeters...
                    MediaBounds mb = pc.GetMediaBounds(mediaName);

                    Point2d p1 = mb.LowerLeftPrintableArea;
                    Point2d p3 = mb.UpperRightPrintableArea;
                    Point2d p2 = new Point2d(p3.X, p1.Y);
                    Point2d p4 = new Point2d(p1.X, p3.Y);

                    // convert millimeters to inches
                    double mm2inch = 25.4;
                    height = p1.GetDistanceTo(p4) / mm2inch;
                    width  = p1.GetDistanceTo(p2) / mm2inch;

                    vpLowerCorner = lo.PlotOrigin;
                    vpUpperCorner = new Point2d(vpLowerCorner.X + width, vpLowerCorner.Y + height);
                    LineSegment2d seg = new LineSegment2d(vpLowerCorner, vpUpperCorner);
                    loCenter = seg.MidPoint;
                    #endregion

                    if (lo.GetViewports().Count == 1) // Viewport was not created by default
                    {
                        // the create by default view ports on new layouts it
                        // is off we need to mark a flag to generate a new one
                        // in another transaction - out of this one
                        flagVp = true;
                    }
                    else if (lo.GetViewports().Count == 2) // create Viewports by default it is on
                    {
                        // extract the last item from the collection
                        // of view ports inside of the layout
                        int      i    = lo.GetViewports().Count - 1;
                        ObjectId vpId = lo.GetViewports()[i];

                        if (!vpId.IsNull)
                        {
                            Viewport vp = tr.GetObject(vpId, OpenMode.ForWrite, false) as Viewport;
                            if (vp != null)
                            {
                                vp.Height      = height;                                   // change height
                                vp.Width       = width;                                    // change width
                                vp.CenterPoint = new Point3d(loCenter.X, loCenter.Y, 0.0); // change center
                                //vp.ColorIndex = 1; // debug

                                // zoom to the Viewport extents
                                Zoom(new Point3d(vpLowerCorner.X, vpLowerCorner.Y, 0.0),
                                     new Point3d(vpUpperCorner.X, vpUpperCorner.Y, 0.0), new Point3d(), 1.0);

                                rvpid = vp.ObjectId; // return the output ObjectId to out...
                            }
                        }
                    }
                }
                tr.Commit();
            } // end of transaction

            // we need another transaction to create a new paper space floating Viewport
            if (flagVp)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt     = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr_ps = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite);

                    Viewport vp = new Viewport();
                    vp.Height      = height;                                   // set the height
                    vp.Width       = width;                                    // set the width
                    vp.CenterPoint = new Point3d(loCenter.X, loCenter.Y, 0.0); // set the center
                    //vp.ColorIndex = 2; // debug

                    btr_ps.AppendEntity(vp);
                    tr.AddNewlyCreatedDBObject(vp, true);

                    vp.On = true; // make it accessible!

                    // zoom to the Viewport extents
                    Zoom(new Point3d(vpLowerCorner.X, vpLowerCorner.Y, 0.0),
                         new Point3d(vpUpperCorner.X, vpUpperCorner.Y, 0.0), new Point3d(), 1.0);

                    rvpid = vp.ObjectId; // return the ObjectId to the out...

                    tr.Commit();
                } // end of transaction
            }
        }
Beispiel #7
0
        public void WindowPlot()

        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())

            {
                var lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                foreach (var ltrId in lt)

                {
                    bool lockZero = false;
                    if (ltrId != db.Clayer && (lockZero || ltrId != db.LayerZero))

                    {
                        var ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite);

                        if (ltr.Name == "TextDel")
                        {
                            ltr.IsPlottable = false;
                        }
                    }
                }

                tr.Commit();
            }


            ed.Regen();
            Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT");

            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
            string path            = db.Filename;
            char   ch              = '\\';
            int    lastIndexOfChar = path.LastIndexOf(ch);
            bool   printOrient     = true;

            path = path.Substring(0, lastIndexOfChar + 1);
            int    iterationCount;
            double scale = 1;

            iterationCount = 0;
            DataSet printBase = new DataSet("AutocadPrintObject");

            System.Data.DataTable drawingTable = new System.Data.DataTable("Drawings");
            printBase.Tables.Add(drawingTable);
            System.Data.DataColumn idColumn = new System.Data.DataColumn("Id", Type.GetType("System.Int32"));
            idColumn.Unique            = true;  // столбец будет иметь уникальное значение
            idColumn.AllowDBNull       = false; // не может принимать null
            idColumn.AutoIncrement     = true;  // будет автоинкрементироваться
            idColumn.AutoIncrementSeed = 1;     // начальное значение
            idColumn.AutoIncrementStep = 1;     // приращении при добавлении новой строки

            System.Data.DataColumn nameColumn       = new System.Data.DataColumn("Name", Type.GetType("System.String"));
            System.Data.DataColumn leftPointXColumn = new System.Data.DataColumn("LeftPointX", Type.GetType("System.Double"));
            leftPointXColumn.DefaultValue = 0; // значение по умолчанию
            System.Data.DataColumn leftPointYColumn = new System.Data.DataColumn("LeftPointY", Type.GetType("System.Double"));
            leftPointXColumn.DefaultValue = 0; // значение по умолчанию
            System.Data.DataColumn rightPointXColumn = new System.Data.DataColumn("RightPointX", Type.GetType("System.Double"));
            System.Data.DataColumn rightPointYColumn = new System.Data.DataColumn("RightPointY", Type.GetType("System.Double"));
            //System.Data.DataColumn drawOrientationColumn = new System.Data.DataColumn("drawOrientation", Type.GetType("System.Bool"));

            drawingTable.Columns.Add(idColumn);
            drawingTable.Columns.Add(nameColumn);
            drawingTable.Columns.Add(leftPointXColumn);
            drawingTable.Columns.Add(leftPointYColumn);
            drawingTable.Columns.Add(rightPointXColumn);
            drawingTable.Columns.Add(rightPointYColumn);
            //drawingTable.Columns.Add(drawOrientationColumn);
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //Выделяем рамкой с координатами x1, y1, x2, y2
                //PromptSelectionResult prRes = ed.GetSelection();
                PromptSelectionResult selRes = ed.SelectAll();
                if (selRes.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nError! \n");
                    return;
                }

                ObjectId[] idsn = selRes.Value.GetObjectIds();
                foreach (ObjectId idn in idsn)
                {
                    Entity entity = (Entity)tr.GetObject(idn, OpenMode.ForRead);
                    if (entity.Layer == "Print")
                    {
                        DataRow row = drawingTable.NewRow();
                        row.ItemArray = new object[] { iterationCount, " ", 0, 0, 0, 0 };
                        drawingTable.Rows.Add(row);
                        Polyline pl = (Polyline)entity;
                        if (pl != null)
                        {
                            int nVertex = pl.NumberOfVertices; // Количество вершин полилинии

                            for (int i = 0; i < nVertex; i++)
                            {
                                Point3d p = pl.GetPoint3dAt(i); // Получаем очередную вершину
                                //ed.WriteMessage("\n\tp[{0}]={1}", i, p);

                                if (i == 0)
                                {
                                    //framePointsX[iterationCount] = p.X;
                                    drawingTable.Rows[iterationCount][2] = p.X;
                                    //framePointsY[iterationCount] = p.Y;
                                    drawingTable.Rows[iterationCount][3] = p.Y;

                                    //ed.WriteMessage("\n\tp[{0}]={1}{2}", i, x2, y2);
                                }
                                if (i == 2)
                                {
                                    //framePointsX1[iterationCount] = p.X;
                                    drawingTable.Rows[iterationCount][4] = p.X;
                                    //framePointsY1[iterationCount] = p.Y;
                                    drawingTable.Rows[iterationCount][5] = p.Y;
                                    //ed.WriteMessage("\n\tp[{0}]={1}{2}", i, x3, y3);
                                }
                            }

                            //Point3d x = pl.GetPoint3dAt(0);
                            //Point3d x1 = pl.GetPoint3dAt(2);
                            //ed.WriteMessage("\n\tp[0]={0}, {1}", framePointsX[iterationCount], framePointsY[iterationCount]);
                            //ed.WriteMessage("\n\tp[2]={0}, {1}", framePointsX1[iterationCount], framePointsY1[iterationCount]);
                            //ed.WriteMessage(x2.ToString(), y2.ToString(), "\n", x3.ToString(), y3.ToString(), "\n");
                        }
                        iterationCount = iterationCount + 1;
                    }
                }
                ed.WriteMessage("\n\titerationCount={0}", iterationCount);
                for (int i = 0; i < iterationCount; i++)
                {
                    //var selectedBooks = drawingTable.Select("Id < 120");
                    //foreach (var b in selectedBooks)
                    // ed.WriteMessage("\n\t{0} - {1}", b["id"], b["LeftPointX"]);
                    PromptSelectionResult prRes;
                    double x1 = Convert.ToDouble(drawingTable.Rows[i][2]);
                    double y1 = Convert.ToDouble(drawingTable.Rows[i][3]);
                    double x2 = Convert.ToDouble(drawingTable.Rows[i][4]);
                    double y2 = Convert.ToDouble(drawingTable.Rows[i][5]);
                    printOrient = (Math.Abs(y2 - y1) > Math.Abs(x2 - x1)) ? true : false;

                    //ed.WriteMessage("\n\tPoint1= {0}, {1}", x1, y1);
                    //ed.WriteMessage("\n\tPoint2= {0}, {1}", x2, y2);
                    prRes = ed.SelectCrossingWindow(new Point3d(x1, y1, 0),
                                                    new Point3d(x2, y2, 0));
                    if (prRes.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    //Создаем коллекцию выделенных объектов
                    ObjectIdCollection objIds = new ObjectIdCollection();

                    ObjectId[] objIdArray = prRes.Value.GetObjectIds();

                    string name    = "123";
                    string PDFname = "123";

                    //Перебираем все объекты в коллекции

                    foreach (ObjectId id in objIdArray)
                    {
                        //Приводим все объекты к типу object
                        Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        //Фильтруем объекты, которые будут переноситься на новый лист
                        if (entity.Layer != "TextDel")
                        {
                            //Добавление нужных объектов
                            objIds.Add(id);
                        }

                        //Ищем в выбранной рамке текст на слое Text
                        if ((entity.GetType() == typeof(DBText)) & (entity.Layer == "Text"))
                        {
                            //Получаем значение объекта DBText на слое Text
                            DBText dt = (DBText)entity;
                            if (dt != null)
                            {
                                //namePrint[iterationCount] = dt.TextString;
                                drawingTable.Rows[i][1] = dt.TextString;
                                //name = path + namePrint[iterationCount] + ".dwg";
                                name    = path + drawingTable.Rows[i][1].ToString() + ".dwg";
                                PDFname = path + drawingTable.Rows[i][1].ToString() + ".pdf";
                            }

                            //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(string.Format("\nLayer:{0}; Type:{1}; Color: {2},{3},{4}\n",
                            //entity.Layer, entity.GetType().ToString(), entity.Color.Red.ToString(), entity.Color.Green.ToString(), entity.Color.Blue.ToString()));
                            //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(name.ToString());
                            //ed.WriteMessage("\n\tЧертеж {0} распечатан! Полный путь: {1}", namePrint[iterationCount], name);
                            //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(name.ToString());
                            //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(path.ToString());
                        }
                    }

                    using (Database newDb = new Database(true, false))

                    {
                        db.Wblock(newDb, objIds, Point3d.Origin, DuplicateRecordCloning.Ignore);

                        string FileName = name;

                        newDb.SaveAs(FileName, DwgVersion.Newest);
                    }
                    ed.WriteMessage("\n\tЧертеж {0} сохранен отдельным файлом! Полный путь: {1}", drawingTable.Rows[i][1].ToString(), name);
                    Point3d first  = new Point3d(x1, y1, 0);
                    Point3d second = new Point3d(x2, y2, 0);

                    // Перевод координат СК UCS в DCS

                    ResultBuffer rbFrom =

                        new ResultBuffer(new TypedValue(5003, 1)),

                                 rbTo =

                        new ResultBuffer(new TypedValue(5003, 2));

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

                    double[] secres = new double[] { 0, 0, 0 };
                    acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres);
                    acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres);
                    Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]);

                    BlockTableRecord btr =

                        (BlockTableRecord)tr.GetObject(

                            db.CurrentSpaceId,

                            OpenMode.ForRead

                            );

                    Layout lo =

                        (Layout)tr.GetObject(

                            btr.LayoutId,

                            OpenMode.ForRead

                            );
                    PlotInfo pi = new PlotInfo();

                    pi.Layout = btr.LayoutId;
                    PlotSettings ps = new PlotSettings(lo.ModelType);

                    ps.CopyFrom(lo);

                    PlotSettingsValidator psv = PlotSettingsValidator.Current;

                    psv.SetPlotWindowArea(ps, window);
                    psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                    psv.SetUseStandardScale(ps, true);
                    psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                    psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);
                    psv.SetPlotCentered(ps, false);
                    psv.SetPlotRotation(ps, PlotRotation.Degrees000);
                    psv.SetUseStandardScale(ps, false);
                    psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)");

                    if (printOrient == true)
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                        psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A2_(594.00_x_420.00_MM)");
                        if ((Math.Abs(secres[0] - firres[0]) / 420) > (Math.Abs(secres[1] - firres[1]) / 594))
                        {
                            scale = (Math.Abs(secres[0] - firres[0]) + 30) / 420;
                        }
                        else
                        {
                            scale = (Math.Abs(secres[1] - firres[1]) + 30) / 594;
                        }
                        psv.SetCustomPrintScale(ps, new CustomScale(1, 1.004 * scale));
                    }

                    else
                    {
                        psv.SetPlotRotation(ps, PlotRotation.Degrees090);
                        psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A1_(594.00_x_841.00_MM)");
                        //psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A2_(594.00_x_420.00_MM)");
                        if ((Math.Abs(secres[0] - firres[0]) / 841) > (Math.Abs(secres[1] - firres[1]) / 594))
                        {
                            scale = (Math.Abs(secres[0] - firres[0]) + 30) / 841;
                        }
                        else
                        {
                            scale = (Math.Abs(secres[1] - firres[1]) + 30) / 594;
                        }
                        psv.SetCustomPrintScale(ps, new CustomScale(1, 1.004 * scale));
                    }
                    //0.7063020
                    //1.41428571429
                    //
                    //psv.SetPlotRotation(ps, printOrient == true ? PlotRotation.Degrees000 : PlotRotation.Degrees090);
                    //psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)");
                    psv.SetPlotCentered(ps, true);
                    pi.OverrideSettings = ps;

                    PlotInfoValidator piv =

                        new PlotInfoValidator();

                    piv.MediaMatchingPolicy =

                        MatchingPolicy.MatchEnabled;

                    piv.Validate(pi);

                    if (PlotFactory.ProcessPlotState ==

                        ProcessPlotState.NotPlotting)

                    {
                        PlotEngine pe =

                            PlotFactory.CreatePublishEngine();

                        using (pe)

                        {
                            // Создаем Progress Dialog (с возможностью отмены пользователем)


                            PlotProgressDialog ppd =

                                new PlotProgressDialog(false, 1, true);

                            using (ppd)

                            {
                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.DialogTitle,

                                    "Custom Plot Progress"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.CancelJobButtonMessage,

                                    "Cancel Job"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.CancelSheetButtonMessage,

                                    "Cancel Sheet"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.SheetSetProgressCaption,

                                    "Sheet Set Progress"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.SheetProgressCaption,

                                    "Sheet Progress"

                                    );

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

                                // Начинаем печать

                                ppd.OnBeginPlot();
                                ppd.IsVisible = true;
                                pe.BeginPlot(ppd, null);

                                pe.BeginDocument(

                                    pi,

                                    doc.Name,

                                    null,

                                    1,

                                    true,

                                    PDFname

                                    );

                                ppd.OnBeginSheet();
                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos        = 0;

                                PlotPageInfo ppi = new PlotPageInfo();

                                pe.BeginPage(

                                    ppi,

                                    pi,

                                    true,

                                    null

                                    );

                                pe.BeginGenerateGraphics(null);
                                pe.EndGenerateGraphics(null);
                                pe.EndPage(null);
                                ppd.SheetProgressPos = 100;
                                ppd.OnEndSheet();

                                // Завершаем работу с документом

                                pe.EndDocument(null);

                                // Завершаем печать

                                ppd.PlotProgressPos = 100;
                                ppd.OnEndPlot();
                                pe.EndPlot(null);
                            }
                        }
                    }

                    else

                    {
                        ed.WriteMessage(

                            "\nAnother plot is in progress."

                            );
                    }
                }
            }

            using (var tr = db.TransactionManager.StartTransaction())

            {
                var lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                foreach (var ltrId in lt)

                {
                    bool lockZero = false;

                    if (ltrId != db.Clayer && (lockZero || ltrId != db.LayerZero))

                    {
                        // Открываем слой для записи

                        var ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite);
                    }
                }

                tr.Commit();
            }
        }
Beispiel #8
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;
        }