Example #1
0
 /// <summary>
 /// 从其它图形数据库中复制打印设置
 /// </summary>
 /// <param name="destdb">目的图形数据库</param>
 /// <param name="sourceDb">源图形数据库</param>
 /// <param name="plotSettingName">打印设置名称</param>
 public static void CopyPlotSettings(this Database destdb, Database sourceDb, string plotSettingName)
 {
     using (Transaction trSource = sourceDb.TransactionManager.StartTransaction())
     {
         using (Transaction trDest = destdb.TransactionManager.StartTransaction())
         {
             //获取源图形数据库的打印设置字典
             DBDictionary dict = trSource.GetObject(sourceDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;
             if (dict != null && dict.Contains(plotSettingName))
             {
                 //获取指定名称的打印设置
                 ObjectId     settingsId = dict.GetAt(plotSettingName);
                 PlotSettings settings   = trSource.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;
                 //新建一个打印设置对象
                 PlotSettings newSettings = new PlotSettings(settings.ModelType);
                 newSettings.CopyFrom(settings);//复制打印设置
                 //将新建的打印设置对象添加到目的数据库的打印设置字典中
                 newSettings.AddToPlotSettingsDictionary(destdb);
                 trDest.AddNewlyCreatedDBObject(newSettings, true);
             }
             trDest.Commit();
         }
         trSource.Commit();
     }
 }
Example #2
0
        private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (DBObject pVpObj = Aux.active_viewport_id(database).GetObject(OpenMode.ForWrite))
            {
                AbstractViewportData pAVD = new AbstractViewportData(pVpObj);
                pAVD.SetView(helperDevice.ActiveView);
            }

            TransactionManager tm = database.TransactionManager;

            using (Transaction ta = tm.StartTransaction())
            {
                using (BlockTableRecord blTableRecord = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForRead))
                {
                    using (Layout pLayObj = (Layout)blTableRecord.LayoutId.GetObject(OpenMode.ForWrite))
                    {
                        PlotSettings    ps           = (PlotSettings)pLayObj;
                        Print.PageSetup pageSetupDlg = new Print.PageSetup(ps);
                        if (pageSetupDlg.ShowDialog() == DialogResult.OK)
                        {
                            ta.Commit();
                        }
                        else
                        {
                            ta.Abort();
                        }
                    }
                }
            }
        }
Example #3
0
        public string[,] GetCanonicalMediaName(Document acDoc)
        {
            Database acCurDb = acDoc.Database;
            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;

            string[] acStrPlDevCol = GetPlotDevice(acDoc);
            string[,] acStrCanMedCol = new string[acStrPlDevCol.Length, 400];
            for (int k = 0; k < acStrPlDevCol.Length; k++)
            {
                using (PlotSettings acPlSet = new PlotSettings(true))
                {
                    bool checkOk = true;
                    try { acPlSetVdr.SetPlotConfigurationName(acPlSet, acStrPlDevCol[k], null); }
                    catch (Autodesk.AutoCAD.Runtime.Exception e) { string Error = e.Message; checkOk = false; }
                    if (!checkOk)
                    {
                        continue;
                    }
                    acPlSetVdr.RefreshLists(acPlSet);
                    StringCollection acCanMedCol = acPlSetVdr.GetCanonicalMediaNameList(acPlSet);
                    for (int l = 0; l < acCanMedCol.Count; l++)
                    {
                        acStrCanMedCol[k, l] = acCanMedCol[l];
                    }
                }
            }
            return(acStrCanMedCol);
        }
Example #4
0
 /// <summary>
 /// 复制另一个图形数据库中的所有打印设置
 /// </summary>
 /// <param name="destdb">目的图形数据库</param>
 /// <param name="sourceDb">源图形数据库</param>
 public static void CopyPlotSettings(this Database destdb, Database sourceDb)
 {
     using (Transaction trSource = sourceDb.TransactionManager.StartTransaction())
     {
         using (Transaction trDest = destdb.TransactionManager.StartTransaction())
         {
             //获取源图形数据库的打印设置字典
             DBDictionary dict = trSource.GetObject(sourceDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;
             //对打印设置字典中的条目进行遍历
             foreach (DBDictionaryEntry entry in dict)
             {
                 //获取指定名称的打印设置
                 ObjectId     settingsId = entry.Value;
                 PlotSettings settings   = trSource.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;
                 //新建一个打印设置对象
                 PlotSettings newSettings = new PlotSettings(settings.ModelType);
                 newSettings.CopyFrom(settings);//复制打印设置
                 //将新建的打印设置对象添加到目的数据库的打印设置字典中
                 newSettings.AddToPlotSettingsDictionary(destdb);
                 trDest.AddNewlyCreatedDBObject(newSettings, true);
             }
             trDest.Commit();
         }
         trSource.Commit();
     }
 }
Example #5
0
 private static void SetPlotSettings(PlotSettings destPlotSettings, PlotSettings sourcePlotSettings)
 {
     destPlotSettings.DrawViewportsFirst  = sourcePlotSettings.DrawViewportsFirst;
     destPlotSettings.PlotHidden          = sourcePlotSettings.PlotHidden;
     destPlotSettings.PlotPlotStyles      = sourcePlotSettings.PlotPlotStyles;
     destPlotSettings.PlotSettingsName    = sourcePlotSettings.PlotSettingsName;
     destPlotSettings.PlotTransparency    = sourcePlotSettings.PlotTransparency;
     destPlotSettings.PlotViewportBorders = sourcePlotSettings.PlotViewportBorders;
     destPlotSettings.PrintLineweights    = sourcePlotSettings.PrintLineweights;
     destPlotSettings.ScaleLineweights    = sourcePlotSettings.ScaleLineweights;
     destPlotSettings.ShadePlot           = sourcePlotSettings.ShadePlot;
     destPlotSettings.ShadePlotCustomDpi  = sourcePlotSettings.ShadePlotCustomDpi;
     destPlotSettings.ShadePlotResLevel   = sourcePlotSettings.ShadePlotResLevel;
     destPlotSettings.ShowPlotStyles      = sourcePlotSettings.ShowPlotStyles;
     using (var psValidator = PlotSettingsValidator.Current)
     {
         // psValidator.SetPlotType(destLayout, sourceLayout.PlotType); // ??? Область печати - просто не меняется, возможно придется задавать границы печати.
         // psValidator.SetCustomPrintScale(sourceLayout, sourceLayout.CustomPrintScale); // ??? масштаб просто не меняется
         if (destPlotSettings.PlotCentered != sourcePlotSettings.PlotCentered)
         {
             psValidator.SetPlotCentered(destPlotSettings, sourcePlotSettings.PlotCentered);
         }
         if (!destPlotSettings.PlotOrigin.IsEqualTo(sourcePlotSettings.PlotOrigin))
         {
             psValidator.SetPlotOrigin(destPlotSettings, sourcePlotSettings.PlotOrigin);
         }
         psValidator.RefreshLists(destPlotSettings);
     }
 }
Example #6
0
 /// <summary>
 /// 复制构造函数,从已有打印设置中获取打印设置
 /// </summary>
 /// <param name="ps">已有打印设置</param>
 public PlotSettingsEx(PlotSettings ps)
     : base(ps.ModelType)
 {
     this.CopyFrom(ps);//从已有打印设置中获取打印设置
     //更新打印设备、图纸尺寸和打印样式表信息
     validator.RefreshLists(this);
 }
Example #7
0
        public static string[] GetPlotDeviceAndCanonicalMediaName()
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Editor   acDocEd = acDoc.Editor;
            PlotSettingsValidator acPlSetVdr  = PlotSettingsValidator.Current;
            StringCollection      acPlDevColl = acPlSetVdr.GetPlotDeviceList();

            for (int i = 0; i < acPlDevColl.Count; i++)
            {
                acDocEd.WriteMessage("\nNumber of device: {0}  -  Device name: {1}", i, acPlDevColl[i]);
            }
            int    n       = GetIntPrompt(acDoc, "Pick number of device to plot", 1, acPlDevColl.Count);
            string acPlDev = acPlDevColl[n];
            string acCanMed;

            Application.ShowAlertDialog("Plot device was chosen: " + acPlDev);
            using (PlotSettings acPlSet = new PlotSettings(true))
            {
                acPlSetVdr.SetPlotConfigurationName(acPlSet, acPlDev, null);
                acPlSetVdr.RefreshLists(acPlSet);
                StringCollection acCanMedColl = acPlSetVdr.GetCanonicalMediaNameList(acPlSet);
                for (int i = 0; i < acCanMedColl.Count; i++)
                {
                    acDocEd.WriteMessage("\nNumber of Canonical media name: {0}  -  Canonical media name: {1}", i, acCanMedColl[i]);
                }
                n        = GetIntPrompt(acDoc, "Pick number of Canonical media name", 1, acCanMedColl.Count);
                acCanMed = acCanMedColl[n];
                Application.ShowAlertDialog("Canonical media name: " + acCanMed);
            }

            return(new string[2] {
                acPlDev, acCanMed
            });
        }
Example #8
0
        /// <summary>
        /// Refreshing list of plot style table
        /// </summary>
        /// <returns></returns>
        public static void RefreshStyles(ComboBox cboStyle)
        {
            // Update devices name
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            PlotSettings          ps  = new PlotSettings(true);

            psv.RefreshLists(ps);

            //Storing current style
            string curStyle = cboStyle.Text;

            // Append style to combobox's items
            StringCollection styleList = psv.GetPlotStyleSheetList();

            cboStyle.Items.Clear();
            for (int i = 0; i < styleList.Count; i++)
            {
                cboStyle.Items.Add(styleList[i]);
            }

            if (styleList.Contains(curStyle))
            {
                cboStyle.Text = curStyle;
            }
            else
            {
                // Setting default plot style table
                cboStyle.SelectedIndex = 0;
            }
        }
Example #9
0
 private void SetPlotSettings(Layout layout, string pageSize, string styleSheet, string device)
 {
     using (var ps = new PlotSettings(layout.ModelType))
     {
         ps.CopyFrom(layout);
         var psv  = PlotSettingsValidator.Current;
         var devs = psv.GetPlotDeviceList();
         if (devs.Contains(device))
         {
             psv.SetPlotConfigurationName(ps, device, null);
             psv.RefreshLists(ps);
         }
         var mns = psv.GetCanonicalMediaNameList(ps);
         if (mns.Contains(pageSize))
         {
             psv.SetCanonicalMediaName(ps, pageSize);
         }
         var ssl = psv.GetPlotStyleSheetList();
         if (ssl.Contains(styleSheet))
         {
             psv.SetCurrentStyleSheet(ps, styleSheet);
         }
         layout.CopyFrom(ps);
     }
 }
Example #10
0
        /// <summary>
        /// Get size of paper of specified device
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="paper"></param>
        private static int[] GetPaperSize(string printer, string paper)
        {
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            PlotSettings          ps  = new PlotSettings(true);

            int[] size = null;
            int   w    = 0;
            int   h    = 0;

            psv.SetPlotConfigurationName(ps, printer, null);
            StringCollection mediaL = psv.GetCanonicalMediaNameList(ps);

            for (int i = 0; i < mediaL.Count; i++)
            {
                string s = (psv.GetLocaleMediaName(ps, i).ToString());
                if (s == paper)
                {
                    paper = mediaL[i];
                    psv.SetPlotConfigurationName(ps, printer, paper);
                    w = Convert.ToInt32(
                        Math.Max(ps.PlotPaperSize.X, ps.PlotPaperSize.Y));
                    h = Convert.ToInt32(
                        Math.Min(ps.PlotPaperSize.X, ps.PlotPaperSize.Y));
                    break;
                }
            }
            if (w != 0 && h != 0)
            {
                size = new int[] { w, h };
            }
            return(size);
        }
Example #11
0
        public void QueryMediaNames()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            LayoutManager         layMgr   = LayoutManager.Current;
            PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current;


            db.TileMode = false;        //goto Paperspace if not already
            ed.SwitchToPaperSpace();    //turn PVP off

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Layout theLayout = (Layout)tr.GetObject(layMgr.GetLayoutId(layMgr.CurrentLayout), OpenMode.ForRead);

                PlotSettings np = new PlotSettings(theLayout.ModelType);
                np.CopyFrom(theLayout);

                //string canMedName = "ANSI_B_(11.00_x_17.00_Inches)"
                StringCollection canMedNames = plSetVdr.GetCanonicalMediaNameList(np);
                ed.WriteMessage("\n{0} MediaNames for {1}", canMedNames.Count, np.PlotConfigurationName);

                int i = 0;
                foreach (string canMedName in canMedNames)
                {
                    ed.WriteMessage("\n{0}: {1} {2}", i, canMedName, plSetVdr.GetLocaleMediaName(np, i));
                    i++;
                }
            }
        }
Example #12
0
        public void QueryPlotStyles()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            LayoutManager         layMgr   = LayoutManager.Current;
            PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current;

            db.TileMode = false;        //goto Paperspace if not already
            ed.SwitchToPaperSpace();    //turn PVP off

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Layout theLayout = (Layout)tr.GetObject(layMgr.GetLayoutId(layMgr.CurrentLayout), OpenMode.ForRead);

                PlotSettings np = new PlotSettings(theLayout.ModelType);
                np.CopyFrom(theLayout);

                //string plotStyle="Monochrome.ctb"
                StringCollection plotStyles = plSetVdr.GetPlotStyleSheetList();
                ed.WriteMessage("\n{0} PlotStyles", plotStyles.Count);

                int i = 0;
                foreach (string plotStyleName in plotStyles)
                {
                    ed.WriteMessage("\n{0}: {1}", i, plotStyleName);
                    i++;
                }
            }
        }
Example #13
0
        /// <summary>
        /// Метод создаёт Layout по заданным параметрам
        /// </summary>
        /// <param name="borders">Границы выделенной области в пространстве модели</param>
        public void CreateLayout(DrawingBorders borders)
        {
            using (Transaction tr = this.wdb.TransactionManager.StartTransaction())
            {
                string layoutName = CheckLayoutName(borders.Name);

                PlotSettings  ps = ImportPlotSettings(borders, tr);
                LayoutManager lm = LayoutManager.Current;
                Layout        layout;
                try
                {
                    layout = (Layout)tr.GetObject(lm.CreateLayout(layoutName), OpenMode.ForWrite);
                }
                catch (System.Exception ex)
                {
                    throw new System.Exception(String.Format("Ошибка создания Layout {0}\n{1}", layoutName, ex.Message));
                }

                layout.CopyFrom(ps);
                lm.CurrentLayout = layout.LayoutName;
                View.Zoom(new Point3d(0, 0, 0), new Point3d(layout.PlotPaperSize.X, layout.PlotPaperSize.Y, 0), new Point3d(), 1);
                CreateViewport(layout, borders, tr);
                tr.Commit();
            }
        }
Example #14
0
        public void PlotPage(PlotInfo info, PlotSettings settings)
        {
            plottedPagesCount++;
            dialog.PlotProgressPos = plottedPagesCount * 100 / pageCount;

            using (PlotPageInfo plotPageInfo = new PlotPageInfo())
            {
                dialog.StatusMsgString = String.Format("Печать {0}: страница {1} из {2}", plotName, plottedPagesCount,
                                                       pageCount);
                dialog.OnBeginSheet();
                dialog.SheetProgressPos        = 0;
                dialog.LowerSheetProgressRange = 0;
                dialog.UpperSheetProgressRange = 100;
                engine.BeginPage(plotPageInfo, info, plottedPagesCount >= pageCount, null);
                engine.BeginGenerateGraphics(null);

                dialog.UpperSheetProgressRange = 50;
                System.Windows.Forms.Application.DoEvents();

                engine.EndGenerateGraphics(null);
                engine.EndPage(null);
                dialog.UpperSheetProgressRange = 100;
                dialog.OnEndSheet();
            }
        }
 public PlotSettingsInfo(PlotSettings pSettings)
 {
     if (pSettings == null)
     {
         throw new ArgumentNullException("PlotSettings");
     }
     this.PSettings = pSettings;
 }
        /// <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));
                    }
                }
            }
        }
Example #17
0
        //if the media size doesn't exist, this will search media list for best match
        // 8.5 x 11 should be there
        private static string setClosestMediaName(PlotSettingsValidator psv, PlotSettings ps,
                                                  double pageWidth, double pageHeight, bool matchPrintableArea)
        {
            //get all of the media listed for plotter
            StringCollection mediaList      = psv.GetCanonicalMediaNameList(ps);
            double           smallestOffest = 0.0;
            string           selectedMedia  = string.Empty;
            PlotRotation     selectedRot    = PlotRotation.Degrees000;

            foreach (string media in mediaList)
            {
                psv.SetCanonicalMediaName(ps, media);

                double mediaWidth  = ps.PlotPaperSize.X;
                double mediaHeight = ps.PlotPaperSize.Y;

                if (matchPrintableArea)
                {
                    mediaWidth  -= (ps.PlotPaperMargins.MinPoint.X + ps.PlotPaperMargins.MaxPoint.X);
                    mediaHeight -= (ps.PlotPaperMargins.MinPoint.Y + ps.PlotPaperMargins.MaxPoint.Y);
                }

                PlotRotation rot = PlotRotation.Degrees090;

                //check that we are not outside the media print area
                if (mediaWidth < pageWidth || mediaHeight < pageHeight)
                {
                    //Check if turning paper will work
                    if (mediaHeight < pageWidth || mediaWidth >= pageHeight)
                    {
                        //still too small
                        continue;
                    }
                    rot = PlotRotation.Degrees090;
                }

                double offset = Math.Abs(mediaWidth * mediaHeight - pageWidth * pageHeight);

                if (selectedMedia == string.Empty || offset < smallestOffest)
                {
                    selectedMedia  = media;
                    smallestOffest = offset;
                    selectedRot    = rot;

                    if (smallestOffest == 0)
                    {
                        break;
                    }
                }
            }
            psv.SetCanonicalMediaName(ps, selectedMedia);
            psv.SetPlotRotation(ps, selectedRot);
            return(selectedMedia);
        }
Example #18
0
        /// <summary>
        /// Apply plot settings to the provided layout.
        /// </summary>
        /// <param name="pageSize">The canonical media name for our page size.</param>
        /// <param name="styleSheet">The pen settings file (ctb or stb).</param>
        /// <param name="devices">The name of the output device.</param>

        public static void SetPlotSettings(
            this Layout lay, string pageSize, string styleSheet, string device
            )
        {
            using (var ps = new PlotSettings(lay.ModelType))
            {
                ps.CopyFrom(lay);

                var psv = PlotSettingsValidator.Current;

                // Set the device

                var devs = psv.GetPlotDeviceList();
                if (devs.Contains(device))
                {
                    psv.SetPlotConfigurationName(ps, device, null);
                    psv.RefreshLists(ps);
                }

                // Set the media name/size

                var mns = psv.GetCanonicalMediaNameList(ps);
                if (mns.Contains(pageSize))
                {
                    psv.SetCanonicalMediaName(ps, pageSize);
                }

                // Set the pen settings

                var ssl = psv.GetPlotStyleSheetList();
                if (ssl.Contains(styleSheet))
                {
                    psv.SetCurrentStyleSheet(ps, styleSheet);
                }

                // Copy the PlotSettings data back to the Layout

                var upgraded = false;
                if (!lay.IsWriteEnabled)
                {
                    lay.UpgradeOpen();
                    upgraded = true;
                }

                lay.CopyFrom(ps);

                if (upgraded)
                {
                    lay.DowngradeOpen();
                }
            }
        }
Example #19
0
        /// <summary>
        /// Refreshing list of plotter
        /// </summary>
        public static void RefreshPloter(ComboBox cboPlotter)
        {
            // Update devices name
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            PlotSettings          ps  = new PlotSettings(true);

            psv.RefreshLists(ps);

            // Store current device's name
            string curPlotter = cboPlotter.Text;

            //Append plotter/printer to combobox
            StringCollection devList = psv.GetPlotDeviceList();

            cboPlotter.Items.Clear();
            for (int i = 0; i < devList.Count; i++)
            {
                if (devList[i] == "None")
                {
                    continue;
                }
                cboPlotter.Items.Add(devList[i]);
            }
            if (devList.Contains(curPlotter))
            {
                cboPlotter.Text = curPlotter;
            }
            else
            {
                //Setting default plotter/printer
                if (devList.Contains("PDF reDirect v2_A3.pc3"))
                {
                    cboPlotter.SelectedIndex =
                        cboPlotter.Items.IndexOf("PDF reDirect v2_A3.pc3");
                }
                else if (devList.Contains("PDF reDirect v2"))
                {
                    cboPlotter.SelectedIndex =
                        cboPlotter.Items.IndexOf("PDF reDirect v2");
                }
                else if (devList.Contains("DWG To PDF.pc3"))
                {
                    cboPlotter.SelectedIndex =
                        cboPlotter.Items.IndexOf("DWG To PDF.pc3");
                }
                else
                {
                    cboPlotter.SelectedIndex = 0;
                }
            }
        }
        public void Plot(string fileName, PlotEngine pe, PlotProgressDialog ppd)
        {
            using (Transaction trans = LayoutID.Database.TransactionManager.StartTransaction())
            {
                Layout layout = (Layout)trans.GetObject(LayoutID, OpenMode.ForRead);
                LayoutManager.Current.CurrentLayout = layout.LayoutName;

                PlotInfo plotInfo = new PlotInfo();
                plotInfo.Layout = LayoutID;

                // Set plot settings
                PlotSettings ps = new PlotSettings(layout.ModelType);
                ps.CopyFrom(layout);

                PlotSettingsValidator psv = PlotSettingsValidator.Current;
                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Layout);
                psv.SetUseStandardScale(ps, true);
                psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);

                /*PlotConfig pConfig = PlotConfigManager.SetCurrentConfig("DWG To PDF.pc3");
                 * var devices = psv.GetPlotDeviceList();*/
                psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", null);
                psv.RefreshLists(ps);
                var media = psv.GetCanonicalMediaNameList(ps);

                psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", GetMediaName());

                plotInfo.OverrideSettings = ps;
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(plotInfo);

                pe.BeginDocument(plotInfo, fileName, null, 1, true, fileName);

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

                PlotPageInfo ppi = new PlotPageInfo();
                pe.BeginPage(ppi, plotInfo, true, null);
                pe.BeginGenerateGraphics(null);
                pe.EndGenerateGraphics(null);

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

                pe.EndDocument(null);
            }
        }
Example #21
0
        public PlotSettings SettingsFor(Destination destination)
        {
            Database     db = destination.Db;
            PlotSettings plotSettingsForSheet = new PlotSettings(true);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary settingsDict =
                    (DBDictionary)tr.GetObject(db.PlotSettingsDictionaryId, OpenMode.ForRead);
                plotSettingsForSheet.CopyFrom(tr.GetObject((ObjectId)settingsDict.GetAt(destination.DictKey),
                                                           OpenMode.ForRead));
                return(plotSettingsForSheet);
            }
        }
Example #22
0
        public static void ChangePlotSetting()
        {
            // 获取当前文档和数据库,启动事务
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 引用布局管理器LayoutManager
                LayoutManager acLayoutMgr;
                acLayoutMgr = LayoutManager.Current;

                // 获取当前布局,在命令行窗口显示布局名
                Layout acLayout;
                acLayout = acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout),
                                             OpenMode.ForRead) as Layout;

                // 输出当前布局名和设备名
                acDoc.Editor.WriteMessage("\nCurrent layout: " +
                                          acLayout.LayoutName);

                acDoc.Editor.WriteMessage("\nCurrent device name: " +
                                          acLayout.PlotConfigurationName);

                // 从布局中获取PlotInfo
                PlotInfo acPlInfo = new PlotInfo();
                acPlInfo.Layout = acLayout.ObjectId;

                // 复制布局中的PlotSettings
                PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                acPlSet.CopyFrom(acLayout);

                // 更新PlotSettings对象的PlotConfigurationName属性
                PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWF6 ePlot.pc3",
                                                    "ANSI_A_(8.50_x_11.00_Inches)");

                // 更新布局
                acLayout.UpgradeOpen();
                acLayout.CopyFrom(acPlSet);

                // 输出已更新的布局设备名
                acDoc.Editor.WriteMessage("\nNew device name: " +
                                          acLayout.PlotConfigurationName);

                // 将新对象保存到数据库
                acTrans.Commit();
            }
        }
Example #23
0
 public TinyPlotter(PlotSettings settings)
 {
     Settings = settings;
     Canvas = new HTMLCanvasElement();
     Canvas.Height = Settings.Height;
     Canvas.Width = Settings.Width;
     Canvas.Style.Border = "1px solid black";
     var ctx = Canvas.GetContext(CanvasTypes.CanvasContext2DType.CanvasRenderingContext2D);
     var image = ctx.CreateImageData(Canvas.Width, Canvas.Height);
     if (Settings.DrawXAxis)
         DrawXAxis(image);
     if (Settings.DrawXAxis)
         DrawYAxis(image);
     ctx.PutImageData(image, 0, 0);
 }
Example #24
0
        /// <summary>
        /// 更新其它的打印设置
        /// </summary>
        /// <param name="psId">打印设置对象</param>
        public void UpdatePlotSettings(ObjectId psId)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;

            using (doc.LockDocument())
                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    PlotSettings ps = psId.GetObject(OpenMode.ForWrite) as PlotSettings;
                    if (ps != null)
                    {
                        ps.CopyFrom(this);//复制当前打印设置
                    }
                    trans.Commit();
                }
        }
Example #25
0
        public void Test()
        {
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            var Text   = new List <string>();
            var editor = Acad.DocumentManager.MdiActiveDocument.Editor;

            System.Collections.Specialized.StringCollection vs = psv.GetPlotDeviceList();
            foreach (var st in vs)
            {
                editor.WriteMessage(st.ToString() + Environment.NewLine);
                Text.Add(st.ToString());
            }
            using (PlotSettings ps = new PlotSettings(false))
            {
                foreach (var st in vs)
                {
                    editor.WriteMessage("Текущий/Selected: " + st.ToString() + Environment.NewLine);
                    Text.Add("Текущий/Selected: " + st.ToString());
                    if (st.ToString() == "AutoCAD PDF (High Quality Print).pc3")
                    {
                        PlotConfig config = PlotConfigManager.SetCurrentConfig(st.ToString());
                        PlotInfo   info   = new PlotInfo();
                        psv.SetPlotConfigurationName(ps, st.ToString(), null);
                        psv.RefreshLists(ps);
                        System.Collections.Specialized.StringCollection mediaName = psv.GetCanonicalMediaNameList(ps);
                        foreach (var media in mediaName)
                        {
                            editor.WriteMessage("Формат/Media name " + media.ToString() + Environment.NewLine);
                            Text.Add("Формат/Media name " + media.ToString());
                            MediaBounds bounds = config.GetMediaBounds(media.ToString());
                            editor.WriteMessage(Math.Round(bounds.PageSize.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.PageSize.Y).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.Y).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString() + Environment.NewLine);
                            Text.Add(Math.Round(bounds.PageSize.X).ToString());
                            Text.Add(Math.Round(bounds.PageSize.Y).ToString());
                            Text.Add(Math.Round(bounds.LowerLeftPrintableArea.X).ToString());
                            Text.Add(Math.Round(bounds.UpperRightPrintableArea.Y).ToString());
                            Text.Add(Math.Round(bounds.UpperRightPrintableArea.X).ToString());
                            Text.Add(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString());
                        }
                    }
                }
            }
            System.IO.File.WriteAllLines("C:\\users\\dyn1\\desktop\\info.txt", Text);
        }
        /// <summary>
        /// Чтение именованных настроек печати из указанного файла
        /// </summary>
        /// <param name="templatePath">Путь к файлу с именованными настройками печати</param>
        /// <returns>Коллекция PlotSettingsInfo</returns>
        public static IEnumerable <PlotSettingsInfo> CreatePlotSettingsInfos(string templatePath)
        {
            Database db = null;
            bool     isTemplateOpened = false;

            DocumentCollection docMan = Application.DocumentManager;
            Document           doc    = docMan.Cast <Document>().FirstOrDefault(d => d.Name.Equals(templatePath, StringComparison.InvariantCulture));

            if (doc != null)
            {
                db = doc.Database;
                isTemplateOpened = true;
            }
            else
            {
                db = new Database(false, true);
                db.ReadDwgFile(templatePath, System.IO.FileShare.Read, true, null);
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary psDict = tr.GetObject(db.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;
                if (psDict != null)
                {
                    foreach (DBDictionaryEntry entry in psDict)
                    {
                        ObjectId     psId = entry.Value;
                        PlotSettings ps   = tr.GetObject(psId, OpenMode.ForRead) as PlotSettings;
                        // Настройки печати для модели и настройки листов самих по себе
                        // нам не нужны
                        // только именованные настройки печати для листов
                        if (!ps.ModelType && !ps.PlotSettingsName.Contains("*"))
                        {
                            PlotSettings newPS = new PlotSettings(false);
                            newPS.CopyFrom(ps);
                            yield return(new PlotSettingsInfo(newPS));
                        }
                    }
                }
                tr.Commit();
            }
            if (!isTemplateOpened)
            {
                db.Dispose();
            }
        }
Example #27
0
        public void QueryDetailedNamedPlotStyles()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current;


            db.TileMode = false;        //goto Paperspace if not already
            ed.SwitchToPaperSpace();    //turn PVP off

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary plotDict = (DBDictionary)db.PlotSettingsDictionaryId.GetObject(OpenMode.ForRead);
                ed.WriteMessage("\n{0} NamedPlotStyles", plotDict.Count);
                int i = 0;
                foreach (DBDictionaryEntry plotDictEntry in plotDict)
                {
                    PlotSettings np = (PlotSettings)tr.GetObject(plotDictEntry.Value, OpenMode.ForRead);
                    ed.WriteMessage("\n{0}: NamedPlotStyle: {1}", i, np.PlotSettingsName);
                    ed.WriteMessage("\n\tPlotter={0}", np.PlotConfigurationName);
                    ed.WriteMessage("\n\tPlotStyle={0}", np.CurrentStyleSheet);
                    ed.WriteMessage("\n\tPlotArea={0}", np.PlotType);

                    StringCollection medNames = plSetVdr.GetCanonicalMediaNameList(np);
                    for (int j = 0; j < medNames.Count; j++)
                    {
                        if (np.CanonicalMediaName.Equals(medNames[j], StringComparison.InvariantCultureIgnoreCase))
                        {
                            ed.WriteMessage("\n\tPlotPaper={0}/\t{1}", plSetVdr.GetLocaleMediaName(np, j), np.CanonicalMediaName);
                            break;
                        }
                    }

                    ed.WriteMessage("\n\tPaperSize={0}", np.PlotPaperSize.ToString());
                    ed.WriteMessage("\n\tPlot Rotation={0}", np.PlotRotation.ToString());
                    ed.WriteMessage("\n\tPaper Margins={0}, {1}", np.PlotPaperMargins.MinPoint.ToString(), np.PlotPaperMargins.MaxPoint.ToString());

                    i++;
                }

                tr.Commit();
            }
        }
Example #28
0
        public static void Apply()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            if (doc == null)
            {
                return;
            }

            var db = doc.Database;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var cs = db.CurrentSpaceId.GetObject(OpenMode.ForRead) as BlockTableRecord;
                if (!cs.IsLayout)
                {
                    return;
                }
                var curLayout = cs.LayoutId.GetObject(OpenMode.ForRead) as Layout;

                using (var curLPS = new PlotSettings(curLayout.ModelType))
                {
                    curLPS.CopyFrom(curLayout);

                    var dicLayouts = db.LayoutDictionaryId.GetObject(OpenMode.ForRead) as DBDictionary;

                    //var lm = LayoutManager.Current;
                    foreach (var item in dicLayouts)
                    {
                        if (item.Key != "Model" && item.Key != curLayout.LayoutName)
                        {
                            //lm.CurrentLayout = item.Key;
                            var layout = item.Value.GetObject(OpenMode.ForWrite) as Layout;
                            using (var lPS = new PlotSettings(layout.ModelType))
                            {
                                lPS.CopyFrom(layout);
                                SetPlotSettings(lPS, curLPS);
                                layout.CopyFrom(lPS);
                            }
                        }
                    }
                }
                t.Commit();
            }
        }
Example #29
0
        /// <summary>
        /// Метод добавляет из объекта границ чертежа новые
        /// именованые настройки печати в файл, если таковых там нет
        /// </summary>
        /// <param name="borders">Объект границ чертежа</param>
        /// <param name="tr">Текущая транзакция</param>
        /// <returns>Настройки печати, соответствующие границам чертежа</returns>
        PlotSettings ImportPlotSettings(DrawingBorders borders, Transaction tr)
        {
            PlotSettings ps = new PlotSettings(false);

            ps.CopyFrom(borders.PSInfo.PSettings);

            DBDictionary psDict = (DBDictionary)tr.GetObject(this.wdb.PlotSettingsDictionaryId,
                                                             OpenMode.ForRead);

            if (!psDict.Contains(ps.PlotSettingsName))
            {
                psDict.UpgradeOpen();
                ps.AddToPlotSettingsDictionary(this.wdb);
                tr.AddNewlyCreatedDBObject(ps, true);
                psDict.DowngradeOpen();
            }
            return(ps);
        }
        /// <summary>
        /// Чтение именованных настроек печати из указанного файла
        /// </summary>
        /// <param name="templatePath">Путь к файлу с именованными настройками печати</param>
        /// <returns>Коллекция PlotSettingsInfo</returns>
        public static IEnumerable<PlotSettingsInfo> CreatePlotSettingsInfos(string templatePath)
        {
            Database db = null;
            bool isTemplateOpened = false;

            DocumentCollection docMan = Application.DocumentManager;
            Document doc = docMan.Cast<Document>().FirstOrDefault(d => d.Name.Equals(templatePath, StringComparison.InvariantCulture));
            if (doc != null)
            {
                db = doc.Database;
                isTemplateOpened = true;
            }
            else
            {
                db = new Database(false, true);
                db.ReadDwgFile(templatePath, System.IO.FileShare.Read, true, null);
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary psDict = tr.GetObject(db.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;
                if (psDict != null)
                {
                    foreach (DBDictionaryEntry entry in psDict)
                    {
                        ObjectId psId = entry.Value;
                        PlotSettings ps = tr.GetObject(psId, OpenMode.ForRead) as PlotSettings;
                        // Настройки печати для модели и настройки листов самих по себе
                        // нам не нужны
                        // только именованные настройки печати для листов
                        if (!ps.ModelType && !ps.PlotSettingsName.Contains("*"))
                        {
                            PlotSettings newPS = new PlotSettings(false);
                            newPS.CopyFrom(ps);
                            yield return new PlotSettingsInfo(newPS);
                        }
                    }
                }
                tr.Commit();
            }
            if (!isTemplateOpened)
                db.Dispose();
        }
Example #31
0
 public CptPlotEngine(Layout layout, string plotConfig)
 {
     this.layout     = layout;
     this.plotConfig = plotConfig;
     defaultbkpltVar = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
     using (var ps = new PlotSettings(layout.ModelType))
     {
         ps.CopyFrom(layout);
         var psv = PlotSettingsValidator.Current;
         psv.SetPlotConfigurationName(ps, plotConfig, null);
         psv.RefreshLists(ps);
         var mcol = psv.GetCanonicalMediaNameList(ps);
         CanonicalMediaNameList = new string[mcol.Count];
         mcol.CopyTo(CanonicalMediaNameList, 0);
         var scol = psv.GetPlotStyleSheetList();
         PlotStyleSheetNameList = new string[scol.Count];
         scol.CopyTo(PlotStyleSheetNameList, 0);
     }
 }
Example #32
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);
                        }
                    }
                }
            }
        }
Example #33
0
        public static void Main()
        {
            var settings = new PlotSettings
            {
                Curves = new List<Curve>(),
                Viewport = new Viewport
                {
                    XMin = -2 * Math.PI,
                    XMax = 2 * Math.PI,
                    YMin = -5,
                    YMax = 5
                },

                Height = 500,
                Width = 800,
                StepX = 0.01,
                DrawXAxis = true,
                DrawYAxis = true
            };

            var layout = new Layout(settings);

            layout.AppendTo(Document.Body);
        }
Example #34
0
        public static 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);
        }
        /// <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);
                    }
                }
            }
        }
Example #36
0
        public Layout(PlotSettings settings)
        {
            var plotter = new TinyPlotter(settings);

            var exprInput = new HTMLInputElement { Type = InputType.Text };
            exprInput.Value = "sin(3x)";

            var evalInput = new HTMLInputElement { Type = InputType.Text };
            evalInput.Value = "plus(5^2, sin(div(pi, 2)))";

            var variableInput = new HTMLInputElement { Type = InputType.Text };
            variableInput.Value = "x";

            var deltaXInput = new HTMLInputElement { Type = InputType.Text };
            deltaXInput.Value = "0.005";

            var xminInput = new HTMLInputElement { Type = InputType.Text };
            xminInput.Value = settings.Viewport.XMin.ToString();

            var xmaxInput = new HTMLInputElement { Type = InputType.Text };
            xmaxInput.Value = settings.Viewport.XMax.ToString();

            var yminInput = new HTMLInputElement { Type = InputType.Text };
            yminInput.Value = settings.Viewport.YMin.ToString();

            var ymaxInput = new HTMLInputElement { Type = InputType.Text };
            ymaxInput.Value = settings.Viewport.YMax.ToString();

            var resultDiv = new HTMLDivElement();
            resultDiv.Style.FontSize = "18px";
            resultDiv.Style.MaxWidth = "300px";

            var btnPlot = new HTMLButtonElement
            {
                InnerHTML = "Plot with derivative",
                OnClick = ev =>
                {
                    Func<HTMLInputElement, bool> IsNaN = x => double.IsNaN(Script.ParseFloat(x.Value));

                    var isNotValid = exprInput.Value == ""
                                  || variableInput.Value == ""
                                  || IsNaN(deltaXInput)
                                  || IsNaN(xminInput)
                                  || IsNaN(xmaxInput)
                                  || IsNaN(yminInput)
                                  || IsNaN(ymaxInput);

                    if (isNotValid)
                    {
                        Write("<h1 style='color:red'>Input is not valid!</h1>", resultDiv);
                        return;
                    }

                    var result = Parser.TryParseInput(exprInput.Value);
                    if (result.WasSuccessful)
                    {
                        // set the settings
                        plotter.Settings.StepX = Script.ParseFloat(deltaXInput.Value);
                        plotter.Settings.Viewport.XMin = Script.ParseFloat(xminInput.Value);
                        plotter.Settings.Viewport.XMax = Script.ParseFloat(xmaxInput.Value);
                        plotter.Settings.Viewport.YMin = Script.ParseFloat(yminInput.Value);
                        plotter.Settings.Viewport.YMax = Script.ParseFloat(ymaxInput.Value);

                        resultDiv.InnerHTML = "";
                        var f = result.Value;
                        var df = Expr.Differentiate(f, variableInput.Value);

                        var fLambda = Expr.Lambdify(f, variableInput.Value);
                        var dfLambda = Expr.Lambdify(df, variableInput.Value);
                        var curveColor = RandomColor();

                        plotter.Settings.Curves.Clear();
                        plotter.Settings.Curves.Add(new Curve { Map = fLambda, Color = curveColor });
                        plotter.Settings.Curves.Add(new Curve { Map = dfLambda, Color = Grayscale(curveColor) });
                        plotter.Draw();

                        var rgbCurveColor = RGB(curveColor);
                        var rgbGrayColor = RGB(Grayscale(curveColor));

                        var msgParsed = "<strong style='color:" + rgbCurveColor + "'>" + f.ToString() + "</strong>";
                        var derivative = "<strong style='color:" + rgbGrayColor + "'>" + df.ToString() + "</strong>";
                        Write("<hr /> Parsed: <br />" + msgParsed + "<br /> Derivative: <br /> " + derivative + "<hr />", resultDiv);
                    }
                    else
                    {
                        var error = string.Join("<br />", result.Expectations);
                        Write("<h1 style='color:red'>" + error + "</h1>", resultDiv);
                    }

                }
            };

            var btnEvaluate = new HTMLButtonElement
            {
                InnerHTML = "Evaluate",
                OnClick = ev =>
                {
                    if (evalInput.Value == "")
                    {
                        Write("<h1 style='color:red'>Input is not valid!</h1>", resultDiv);
                        return;
                    }

                    var result = Parser.TryParseInput(evalInput.Value);
                    if (result.WasSuccessful)
                    {
                        resultDiv.InnerHTML = "";
                        var expression = result.Value;
                        var eval = Expr.Evaluate(expression);

                        Write("<h4 style='color:green'>" +
                                "Parsed: " + expression.ToString() + "<br />" +
                                "Answer: " + eval.ToString()
                            + "</h4>", resultDiv);
                    }
                    else
                    {
                        var error = string.Join("<br />", result.Expectations);
                        Write("<h1 style='color:red'>" + error + "</h1>", resultDiv);
                    }

                }
            };

            var slider = new HTMLInputElement { Type = InputType.Range };

            btnEvaluate.Style.Width = "90%";
            btnEvaluate.Style.Margin = "5px";
            btnEvaluate.Style.Height = "40px";
            btnPlot.Style.Margin = "5px";
            btnPlot.Style.Height = "40px";
            btnPlot.Style.Width = "90%";

            var layout = Table(
                    Row(Table(
                            Row(Label("Expression"), exprInput),
                            Row(Label("Variable"), variableInput),
                            Row(Label("XAxis step"), deltaXInput),
                            Row(Label("XMin"), xminInput),
                            Row(Label("XMax"), xmaxInput),
                            Row(Label("YMin"), yminInput),
                            Row(Label("YMax"), ymaxInput),
                            Row(btnPlot, 2),
                            Row(new HTMLHRElement(), 2),
                            Row(Label("Expression"), evalInput),
                            Row(btnEvaluate, 2),
                            Row(resultDiv, 2)),
                        Table(
                            Row(plotter.Canvas)))
                );

            this.container = layout;
        }
        public void PlotToPDF()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;


            //var filename = doc.Name.Split('.');
            
            var filePathArray = db.Filename.Split('\\');
            var filename = filePathArray[filePathArray.Length - 1].Split('.')[0];


            Transaction tr =
              db.TransactionManager.StartTransaction();
            using (tr)
            {

                // We'll be plotting the current layout

                Application.DocumentManager.MdiActiveDocument = doc;
                LayoutManager.Current.CurrentLayout = GetFirstLayout();

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                // We need a PlotInfo object
                // linked to the layout

                PlotInfo pi = new PlotInfo();
                pi.Layout = btr.LayoutId;

                // We need a PlotSettings object
                // based on the layout settings
                // which we then customize

                PlotSettings ps = new PlotSettings(lo.ModelType);
                ps.CopyFrom(lo);

                // The PlotSettingsValidator helps
                // create a valid PlotSettings object

                PlotSettingsValidator psv =
                  PlotSettingsValidator.Current;

                // We'll plot the extents, centered and
                // scaled to fit

                psv.SetPlotType(
                  ps,
                  Autodesk.AutoCAD.DatabaseServices.PlotType.Extents
                );
                psv.SetUseStandardScale(ps, true);
                psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                psv.SetPlotCentered(ps, true);
                psv.RefreshLists(ps);
                psv.SetCurrentStyleSheet(lo, "C:\\ProgramData\\Autodesk\\ACA 2015\\enu\\Plotters\\Plot Styles\\COWI_EL-v00.ctb");

                // We'll use the standard DWF PC3, as
                // for today we're just plotting to file

                psv.SetPlotConfigurationName(
                  ps,
                  "DWG to PDF.pc3",
                  "ISO_A0_(841.00_x_1189.00_MM)"
                );

                // We need to link the PlotInfo to the
                // PlotSettings and then validate it

                pi.OverrideSettings = ps;
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(pi);

                // A PlotEngine does the actual plotting
                // (can also create one for Preview)

                if (PlotFactory.ProcessPlotState ==
                    ProcessPlotState.NotPlotting)
                {
                    PlotEngine pe = PlotFactory.CreatePublishEngine();
                    using (pe)
                    {
                        // Create a Progress Dialog to provide info
                        // and allow the user to cancel

                        PlotProgressDialog ppd = new PlotProgressDialog(true, 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;

                            // 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
                              "E:\\Plottfefiløving\\PDF\\" + filename + ".pdf"
                            );

                            // Which contains a single sheet

                            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);

                            // 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."
                    );
                }
            }
        }
Example #38
0
        /// <summary>
        /// Метод добавляет из объекта границ чертежа новые
        /// именованые настройки печати в файл, если таковых там нет
        /// </summary>
        /// <param name="borders">Объект границ чертежа</param>
        /// <param name="tr">Текущая транзакция</param>
        /// <returns>Настройки печати, соответствующие границам чертежа</returns>
        PlotSettings ImportPlotSettings(DrawingBorders borders, Transaction tr)
        {
            PlotSettings ps = new PlotSettings(false);
            ps.CopyFrom(borders.PSInfo.PSettings);

            DBDictionary psDict = (DBDictionary)tr.GetObject(this.wdb.PlotSettingsDictionaryId,
                                                             OpenMode.ForRead);
            if (!psDict.Contains(ps.PlotSettingsName))
            {
                psDict.UpgradeOpen();
                ps.AddToPlotSettingsDictionary(this.wdb);
                tr.AddNewlyCreatedDBObject(ps, true);
                psDict.DowngradeOpen();
            }
            return ps;
        }