Esempio n. 1
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;
            }
        }
Esempio n. 2
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
            });
        }
Esempio n. 3
0
 /// <summary>
 /// 复制构造函数,从已有打印设置中获取打印设置
 /// </summary>
 /// <param name="ps">已有打印设置</param>
 public PlotSettingsEx(PlotSettings ps)
     : base(ps.ModelType)
 {
     this.CopyFrom(ps);//从已有打印设置中获取打印设置
     //更新打印设备、图纸尺寸和打印样式表信息
     validator.RefreshLists(this);
 }
Esempio n. 4
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);
        }
        /// <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));
                    }
                }
            }
        }
        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);
            }
        }
Esempio n. 7
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;
                }
            }
        }
Esempio n. 8
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);
        }
Esempio n. 9
0
        /// <summary>
        /// 将打印设备及标准图纸尺寸清单存储到XML文件
        /// </summary>
        /// <param name="fileName">XML文件名</param>
        public static void DeviceMeidaToXML(string fileName)
        {
            XElement xroot = new XElement("Root");//创建一个XML根元素
            //获取当前打印设备列表
            PlotSettingsValidator psv     = PlotSettingsValidator.Current;
            StringCollection      devices = psv.GetPlotDeviceList();
            //创建打印设置对象,以获取设备拥有的图纸尺寸
            PlotSettings ps = new PlotSettings(true);

            foreach (string device in devices)//遍历打印设备
            {
                //创建一个名为Device的新元素
                XElement xDevice = new XElement("Device");
                //在Device元素下添加表示设备名称的属性
                xDevice.Add(new XAttribute("Name", device));
                //更新打印设备、图纸尺寸,以反映当前系统状态。
                psv.SetPlotConfigurationName(ps, device, null);
                psv.RefreshLists(ps);
                //获取打印设备的所有可用标准图纸尺寸的名称
                StringCollection medias = psv.GetCanonicalMediaNameList(ps);
                foreach (string media in medias)
                {
                    //如果为用户自定义图纸尺寸,则结束本次循环
                    if (media == "UserDefinedMetric")
                    {
                        continue;
                    }
                    //创建一个名为Media的新元素
                    XElement xMedia = new XElement("Media");
                    //在Media元素下添加表示图纸尺寸的属性
                    xMedia.Add(new XAttribute("Name", media));
                    xDevice.Add(xMedia); //添加Media元素到Device元素中
                }
                xroot.Add(xDevice);      //添加Device元素到根元素中
            }
            xroot.Save(fileName);        //保存XML文件
        }
Esempio n. 10
0
        public PageSetup(PlotSettings ps)
        {
            InitializeComponent();
            textBoxPlotScaleDrawingUint.LostFocus += new EventHandler(textBoxPlotScalePaperUint_TextChanged);
            textBoxPlotScalePaperUint.LostFocus   += new EventHandler(textBoxPlotScalePaperUint_TextChanged);
            textBoxPlotOffsetX.LostFocus          += new EventHandler(textBoxPlotOffsetX_TextChanged);
            textBoxPlotOffsetY.LostFocus          += new EventHandler(textBoxPlotOffsetX_TextChanged);
            textBoxDPI.LostFocus += new EventHandler(textBoxDPI_TextChanged);

            m_plotStg        = ps;
            m_plotSettingVal = PlotSettingsValidator.Current;

            // fill device list
            m_plotSettingVal.RefreshLists(m_plotStg);

            // is stored device name available in system ?
            String deviceName = m_plotStg.PlotConfigurationName;
            String mediaName  = m_plotStg.CanonicalMediaName;

            setPlotCfgName2Validator(deviceName, mediaName, false);

            FillDeviceCombo();

            FillPaperOrientation();
            comboBoxDevices.SelectedItem = deviceName;

            FillPlotAreaCombo(true);
            FillPlotOffset();

            FillScaleValues(true);
            FillPlotStyles();
            FillShadePlotQualityDPI(true);
            FillPlotStyleCombo(true);
            FillViewCombo(true);
            FillWindowArea();
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
            public void PublishNew(string pdfLocation, string layerName)
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;

                Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication.GetType().InvokeMember("ZoomExtents", BindingFlags.InvokeMethod, null, Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication, null);
                Database db = doc.Database;
                Editor   ed = doc.Editor;

                string dwgFileName =
                    Application.GetSystemVariable("DWGNAME") as string;
                string dwgPath =
                    Application.GetSystemVariable("DWGPREFIX") as string;

                string name =
                    System.IO.Path.GetFileNameWithoutExtension(dwgFileName);

                //find a temp location.
                string strTemp = System.IO.Path.GetTempPath();

                //PromptStringOptions options =
                //    new PromptStringOptions("Specific the DWF file name");
                //options.DefaultValue = "c:\\temp\\" + name + ".dwf";
                //PromptResult result = ed.GetString(options);

                //if (result.Status != PromptStatus.OK)
                //    return;

                //get the layout ObjectId List
                System.Collections.ArrayList layoutList = null;
                try
                {
                    layoutList = layouts;
                }
                catch
                {
                    //  Application.ShowAlertDialog("Unable to get layouts name");
                    return;
                }

                Publisher publisher = Application.Publisher;

                //put the plot in foreground
                short bgPlot =
                    (short)Application.GetSystemVariable("BACKGROUNDPLOT");

                Application.SetSystemVariable("BACKGROUNDPLOT", 0);

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

                    Layout _layout = null;
                    foreach (ObjectId layoutId in layoutList)
                    {
                        Layout layout = tr.GetObject(layoutId, OpenMode.ForWrite) as Layout;

                        #region plot Extends

                        Point3d pMin = layout.Extents.MinPoint;
                        Point3d pMax = layout.Extents.MaxPoint;
                        PlotSettingsValidator psv = PlotSettingsValidator.Current;
                        PlotSettings          ps  = new PlotSettings(layout.ModelType);
                        ps.CopyFrom(layout);
                        psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                        bool bAreaIsLandscape = true;
                        if (layout.ModelType)
                        {
                            bAreaIsLandscape = (db.Extmax.X - db.Extmin.X) > (db.Extmax.Y - db.Extmin.Y) ? true : false;
                        }
                        else
                        {
                            bAreaIsLandscape = (layout.Extents.MaxPoint.X - layout.Extents.MinPoint.X) > (layout.Extents.MaxPoint.Y - layout.Extents.MinPoint.Y) ? true : false;
                        }

                        bool bPaperIsLandscape = (ps.PlotPaperSize.X > ps.PlotPaperSize.Y) ? true : false;
                        if (bPaperIsLandscape != bAreaIsLandscape)
                        {
                            psv.SetPlotRotation(ps, PlotRotation.Degrees270);
                        }
                        ps.PlotSettingsName = layout.LayoutName + "_plot";
                        ps.AddToPlotSettingsDictionary(db);
                        tr.AddNewlyCreatedDBObject(ps, true);
                        psv.RefreshLists(ps);
                        layout.CopyFrom(ps);

                        #endregion

                        DsdEntry entry = new DsdEntry();

                        entry.DwgName = dwgPath + dwgFileName;
                        entry.Layout  = layout.LayoutName;
                        entry.Title   = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layerName + "-" + layout.LayoutName;
                        entry.Nps     = ps.PlotSettingsName;// "AA";
                        _layout       = layout;
                        collection.Add(entry);
                    }

                    DsdData dsdData = new DsdData();

                    dsdData.SheetType       = SheetType.SinglePdf;
                    dsdData.ProjectPath     = pdfLocation;
                    dsdData.DestinationName = pdfLocation + name + " " + layerName + ".pdf";


                    dsdData.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
                    dsdData.SetUnrecognizedData("PromptForPwd", "FALSE");
                    dsdData.SetUnrecognizedData("INCLUDELAYER", "FALSE");
                    dsdData.NoOfCopies    = 1;
                    dsdData.IsHomogeneous = false;

                    string dsdFile = pdfLocation + name + layerName + ".dsd";

                    if (System.IO.File.Exists(dsdFile))
                    {
                        System.IO.File.Delete(dsdFile);
                    }

                    dsdData.SetDsdEntryCollection(collection);
                    dsdData.PromptForDwfName = false;

                    //Workaround to avoid promp for dwf file name
                    //set PromptForDwfName=FALSE in
                    //dsdData using StreamReader/StreamWriter
                    dsdData.WriteDsd(dsdFile);

                    StreamReader sr  = new StreamReader(dsdFile);
                    string       str = sr.ReadToEnd();
                    sr.Close();

                    //str =
                    //    str.Replace("PromptForDwfName=TRUE",
                    //                    "PromptForDwfName=FALSE");
                    str =
                        str.Replace("IncludeLayer=TRUE",
                                    "IncludeLayer=FALSE");

                    StreamWriter sw = new StreamWriter(dsdFile);
                    sw.Write(str);
                    sw.Close();

                    dsdData.ReadDsd(dsdFile);

                    //18-07-2018
                    //PlotSettings ps = new PlotSettings(_layout.ModelType);
                    //ps.CopyFrom(_layout);

                    //PlotSettingsValidator psv = PlotSettingsValidator.Current;
                    //psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                    //psv.SetUseStandardScale(ps, true);
                    //psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                    //psv.SetPlotCentered(ps, true);


                    //// We'll use the standard DWF PC3, as

                    //// for today we're just plotting to file


                    //psv.SetPlotConfigurationName(ps, "DWG to PDF.PC3", "ANSI_A_(8.50_x_11.00_Inches)");

                    using (PlotConfig pc = PlotConfigManager.SetCurrentConfig("DWG to PDF.PC3"))
                    {
                        publisher.PublishExecute(dsdData, pc);
                    }

                    System.IO.File.Delete(dsdFile);

                    tr.Commit();
                }

                //reset the background plot value
                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);
            }
Esempio n. 13
0
        //set up plotinfo
        static public PlotInfo plotSetUp(Extents2d window, Transaction tr, Database db, Editor ed, bool scaleToFit, bool pdfout)
        {
            using (tr)
            {
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                // We need a PlotInfo object linked to the layout
                PlotInfo pi = new PlotInfo();
                pi.Layout = btr.LayoutId;

                //current layout
                Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

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

                //set rotation
                psv.SetPlotRotation(ps, orientation(window)); //perhaps put orientation after window setting window??

                // We'll plot the window, centered, scaled, landscape rotation
                psv.SetPlotWindowArea(ps, window);
                psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);//breaks here on some drawings

                // Set the plot scale
                psv.SetUseStandardScale(ps, true);
                if (scaleToFit == true)
                {
                    psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
                }
                else
                {
                    psv.SetStdScaleType(ps, StdScaleType.StdScale1To1);
                }

                // Center the plot
                psv.SetPlotCentered(ps, true);//finding best location

                //get printerName from system settings
                PrinterSettings settings           = new PrinterSettings();
                string          defaultPrinterName = settings.PrinterName;

                psv.RefreshLists(ps);
                // Set Plot device & page size
                // if PDF set it up for some PDF plotter
                if (pdfout == true)
                {
                    psv.SetPlotConfigurationName(ps, "DWG to PDF.pc3", null);
                    var mns = psv.GetCanonicalMediaNameList(ps);
                    if (mns.Contains("ANSI_expand_A_(8.50_x_11.00_Inches)"))
                    {
                        psv.SetCanonicalMediaName(ps, "ANSI_expand_A_(8.50_x_11.00_Inches)");
                    }
                    else
                    {
                        string mediaName = setClosestMediaName(psv, ps, 8.5, 11, true);
                    }
                }
                else
                {
                    psv.SetPlotConfigurationName(ps, defaultPrinterName, null);
                    var mns = psv.GetCanonicalMediaNameList(ps);
                    if (mns.Contains("Letter"))
                    {
                        psv.SetCanonicalMediaName(ps, "Letter");
                    }
                    else
                    {
                        string mediaName = setClosestMediaName(psv, ps, 8.5, 11, true);
                    }
                }

                //rebuilts plotter, plot style, and canonical media lists
                //(must be called before setting the plot style)
                psv.RefreshLists(ps);

                //ps.ShadePlot = PlotSettingsShadePlotType.AsDisplayed;
                //ps.ShadePlotResLevel = ShadePlotResLevel.Normal;

                //plot options
                //ps.PrintLineweights = true;
                //ps.PlotTransparency = false;
                //ps.PlotPlotStyles = true;
                //ps.DrawViewportsFirst = true;
                //ps.CurrentStyleSheet

                // Use only on named layouts - Hide paperspace objects option
                // ps.PlotHidden = true;

                //psv.SetPlotRotation(ps, PlotRotation.Degrees180);


                //plot table needs to be the custom heavy lineweight for the Uphol specs
                psv.SetCurrentStyleSheet(ps, "monochrome.ctb");

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

                return(pi);
            }
        }
Esempio n. 14
0
        public static void SaveAsPDF(ResultBuffer rbArgs)
        {
            var editor = Acad.DocumentManager.MdiActiveDocument.Editor;

            editor.WriteMessage("Процесс экспорта чертежей в формат PDF начинается...");
            // Получение директории и параметров поиска
            if (rbArgs != null)
            {
                string str     = "";
                bool   subDirs = false;
                foreach (TypedValue rb in rbArgs)
                {
                    if (rb.TypeCode == (int)Autodesk.AutoCAD.Runtime.LispDataType.Text)
                    {
                        if (rb.Value.ToString() == "true")
                        {
                            subDirs = true;
                        }
                        else if (rb.Value.ToString() == "false")
                        {
                            subDirs = false;
                        }
                        else
                        {
                            str += rb.Value.ToString();
                        }
                    }
                }
                Acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Путь к чертежам: " + str);
                // Получение списка файлов с учетом заданного пути и параметров поиска
                try
                {
                    str = str.Replace('/', '\\');
                    System.IO.DirectoryInfo rootDir = new System.IO.DirectoryInfo(str);
                    System.IO.FileInfo[]    dirs    = rootDir.GetFiles("*.dwg", subDirs ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                    short bgp = (short)Acad.GetSystemVariable("BACKGROUNDPLOT");
                    Acad.SetSystemVariable("BACKGROUNDPLOT", 0);
                    //Список листов найденных чертежей
                    foreach (FileInfo dir in dirs)
                    {
                        editor.WriteMessage(Environment.NewLine + dir);
                        using (Database dwgDB = new Database(false, true))
                        {
                            dwgDB.ReadDwgFile(dir.FullName, System.IO.FileShare.ReadWrite, false, "");


                            //Далее манипуляции с базой данных чертежа
                            using (Transaction acTrans = dwgDB.TransactionManager.StartTransaction())
                            {
                                List <Layout> layouts    = new List <Layout>();
                                DBDictionary  layoutDict = (DBDictionary)acTrans.GetObject(dwgDB.LayoutDictionaryId, OpenMode.ForRead);
                                editor.WriteMessage("Листы чертежа " + dir + ":");
                                foreach (DBDictionaryEntry id in layoutDict)
                                {
                                    if (id.Key != "Model")
                                    {
                                        Layout                ltr    = (Layout)acTrans.GetObject((ObjectId)id.Value, OpenMode.ForRead);
                                        PlotConfig            config = PlotConfigManager.SetCurrentConfig("AutoCAD PDF (High Quality Print).pc3");
                                        PlotSettingsValidator psv    = PlotSettingsValidator.Current;
                                        PlotSettings          ps     = new PlotSettings(ltr.ModelType);
                                        psv.SetPlotConfigurationName(ps, "AutoCAD PDF (High Quality Print).pc3", null);
                                        psv.RefreshLists(ps);
                                        layouts.Add(ltr);
                                        editor.WriteMessage(Environment.NewLine + ltr.LayoutName);
                                        editor.WriteMessage(Environment.NewLine + ltr.PlotPaperSize.ToString());
                                        editor.WriteMessage(Environment.NewLine + ltr.PlotSettingsName);
                                    }
                                }
                                layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
                                string filename = Path.ChangeExtension(dwgDB.Filename, "pdf");

                                MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
                                plotter.Publish();
                                editor.WriteMessage(Environment.NewLine + dwgDB.Filename + " успешно экспортирован");
                                acTrans.Commit();
                            }
                        }
                    }
                    Acad.SetSystemVariable("BACKGROUNDPLOT", bgp);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {
                    editor.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
                }
            }
        }
Esempio n. 15
0
        public static ResultDTO plotTest(string id, string file, string fileID, bool isSnap = false)
        {
            try
            {
                Document doc = Application.DocumentManager.Open(file, false);
                Application.DocumentManager.MdiActiveDocument = doc;

                PlotSettings ps     = null; //声明增强型打印设置对象
                Layout       layout = null; //当前布局对象
                bool         isTile = AppConfig.GetAppSettings("ViewMode").ToLower().Trim() == "tilepicviewer";
                using (Transaction trans = doc.Database.TransactionManager.StartTransaction())
                {
                    LayoutManager lm = LayoutManager.Current;//获取当前布局管理器
                    layout = (Layout)GetLayoutId(doc.Database, lm.CurrentLayout).GetObject(OpenMode.ForRead);

                    ps = new PlotSettings(layout.ModelType);
                    ps.CopyFrom(layout);//从已有打印设置中获取打印设置

                    //0.更新打印设备、图纸尺寸和打印样式表信息
                    PlotSettingsValidator validator = PlotSettingsValidator.Current;
                    validator.RefreshLists(ps);
                    //1.设置打印驱动
                    string plotConfigurationName = AppConfig.GetAppSettings("Printer");
                    if (isSnap)
                    {
                        plotConfigurationName = "PublishToWeb JPG.pc3";
                    }
                    validator.SetPlotConfigurationName(ps, plotConfigurationName, null);

                    //2.设置打印纸张
                    StringCollection cMNameLst = validator.GetCanonicalMediaNameList(ps);
                    string           mediaName = AppConfig.GetAppSettings("CanonicalMediaName");
                    if (isSnap)
                    {
                        mediaName = "VGA (480.00 x 640.00 像素)";
                    }
                    bool             isHas = false;
                    StringCollection canonicalMediaNames = validator.GetCanonicalMediaNameList(ps);
                    foreach (string canonicalMediaName in canonicalMediaNames)
                    {
                        string localeMediaName = validator.GetLocaleMediaName(ps, canonicalMediaName);
                        if (localeMediaName == mediaName)
                        {
                            validator.SetCanonicalMediaName(ps, canonicalMediaName);
                            isHas = true;
                            break;
                        }
                    }
                    if (!isHas)
                    {
                        throw new System.Exception("纸张:" + mediaName + "不存在!");
                    }
                    //3.设置打印样式表
                    string plotStyleSheet = AppConfig.GetAppSettings("PlotStyleSheet");
                    validator.SetCurrentStyleSheet(ps, plotStyleSheet);

                    validator.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                    validator.SetPlotCentered(ps, true);
                    validator.SetUseStandardScale(ps, true);
                    validator.SetStdScaleType(ps, StdScaleType.ScaleToFit);//设置打印时布满图纸

                    validator.SetPlotRotation(ps, PlotRotation.Degrees000);
                    trans.Commit();
                }

                PlotConfig config = PlotConfigManager.CurrentConfig;
                doc = AcadApp.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                //获取去除扩展名后的文件名(不含路径)
                string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(doc.Name, "dwg");
                //存放在同目录下
                var basePath = AppConfig.GetAppSettings("CacheViewFilePath");
                if (!basePath.EndsWith("\\"))
                {
                    basePath += "\\";
                }

                int    num  = Convert.ToInt32(fileID) / 1000 + 1;
                string root = basePath + "Dwg\\" + string.Format("{0}", num.ToString("D8")) + "\\";
                if (!isTile)
                {
                    root = Path.Combine(basePath, string.Format("{0}", num.ToString("D8")) + "\\");
                }
                if (!Directory.Exists(@root))
                {
                    Directory.CreateDirectory(@root);
                }

                fileName = root + id + config.DefaultFileExtension;
                if (!isTile || isSnap)
                {
                    fileName = root + fileID + config.DefaultFileExtension;
                }

                //为了防止后台打印问题,必须在调用打印API时设置BACKGROUNDPLOT系统变量为0
                short backPlot = (short)AcadApp.GetSystemVariable("BACKGROUNDPLOT");
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", 0);

                PlotEngine plotEngine = PlotFactory.CreatePublishEngine(); //创建一个打印引擎
                PlotInfo   pi         = new PlotInfo();                    //创建打印信息
                pi.Layout           = layout.ObjectId;                     //要打印的布局
                pi.OverrideSettings = ps;                                  //使用ps中的打印设置

                //验证打印信息是否有效
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(pi);

                PlotPageInfo ppi = new PlotPageInfo();
                plotEngine.BeginPlot(null, null);
                plotEngine.BeginDocument(pi, doc.Name, null, 1, true, fileName);
                plotEngine.BeginPage(ppi, pi, true, null);
                plotEngine.BeginGenerateGraphics(null);
                plotEngine.EndGenerateGraphics(null);
                plotEngine.EndPage(null);
                plotEngine.EndDocument(null);
                plotEngine.EndPlot(null);

                plotEngine.Destroy();//销毁打印引擎

                //恢复BACKGROUNDPLOT系统变量的值
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", backPlot);

                doc.CloseAndDiscard();

                if (!File.Exists(fileName))
                {
                    throw new System.Exception("打印文件生成失败!");
                }

                ResultDTO reVal = new ResultDTO();
                if (isTile && !isSnap)//如果是图片就切图
                {
                    var img = new ZoomifyImage(fileName, 1024);
                    img.Zoomify(root + id + "\\");

                    reVal.status        = true;
                    reVal.DirectoryPath = "/" + id + "/";
                    reVal.ZoomLevel     = img.ZoomLevels - 1;
                }
                else
                {
                    reVal.status = true;
                }

                try
                {
                    //强制删除过程打印文件
                    if (File.Exists(file) && !isSnap)
                    {
                        File.Delete(file);
                    }
                }
                catch { }

                return(reVal);
            }
            catch (System.Exception e)
            {
                return(new ResultDTO
                {
                    status = false,
                    ErrInfo = e.Message,
                    FileName = file
                });
            }
        }
Esempio n. 16
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
            }
        }
Esempio n. 17
0
        public void PlotToPDF(string filePath)
        {
            if (File.Exists(filePath))
            {
                Application.ShowAlertDialog("File already exists");
                return;
            }

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



            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, "E:\\Plottefil\\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
                                filePath);

                            // 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."
                        );
                }
            }
        }
Esempio n. 18
0
        public static void InKhungTen(BlockTableRecord acBlkTblRecSpc, Extents2d PlotArea, string path, string PlotDevice, string CanonicalMediaName)
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            //string folder = DirectoryFolder(ac.Database.OriginalFileName);
            //string filename = DocumentShortName(ac.Database.OriginalFileName) + ".pdf";
            //Application.ShowAlertDialog(path);
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Application.SetSystemVariable("BACKGROUNDPLOT", 0);

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

                PlotInfo acPtInfo = new PlotInfo();
                acPtInfo.Layout = acLayout.ObjectId;

                PlotSettings acPtSet = new PlotSettings(acLayout.ModelType);
                acPtSet.CopyFrom(acLayout);

                PlotSettingsValidator acPtSetVlr = PlotSettingsValidator.Current;
                //acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                acPtSetVlr.RefreshLists(acPtSet);
                acPtSetVlr.SetPlotWindowArea(acPtSet, PlotArea);
                acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                acPtSetVlr.SetUseStandardScale(acPtSet, true);
                acPtSetVlr.SetStdScaleType(acPtSet, StdScaleType.ScaleToFit);
                acPtSetVlr.SetPlotCentered(acPtSet, true);
                acPtSetVlr.SetCurrentStyleSheet(acPtSet, "monochrome.ctb");
                //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_full_bleed_A1_(594.00_x_841.00_MM)");
                //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_A1_(594.00_x_841.00_MM)");
                acPtSetVlr.SetPlotConfigurationName(acPtSet, acPlDev, acCanMed);
                //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWF6 ePlot.pc3", "ANSI_A_(8.50_x_11.00_Inches)");
                acPtInfo.OverrideSettings           = acPtSet;
                LayoutManager.Current.CurrentLayout = acLayout.LayoutName;

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

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

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

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

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

                            //Define the plot output
                            acPtEng.BeginDocument(acPtInfo, acDoc.Name, null, 1, true, @path);

                            //Display the process message
                            acPtProgDlg.set_PlotMsgString(PlotMessageIndex.Status, "Plotting " + acDoc.Name + " - " + acLayout.LayoutName);

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

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

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

                            //End document
                            acPtEng.EndDocument(null);

                            //End plot
                            acPtProgDlg.PlotProgressPos = 100;
                            acPtProgDlg.OnEndPlot();
                            acPtEng.EndPlot(null);
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        public void QueryPaperSize()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

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

            Dictionary <string, Point2d> customPaperSize = new Dictionary <string, Point2d>(StringComparer.CurrentCultureIgnoreCase);

            customPaperSize.Add("A4", new Point2d(210.0, 297.0));
            customPaperSize.Add("A3", new Point2d(297.0, 420.0));
            customPaperSize.Add("A2", new Point2d(420.0, 594.0));
            customPaperSize.Add("A1", new Point2d(594.0, 841.0));
            customPaperSize.Add("A0", new Point2d(841.0, 1189.0));
            customPaperSize.Add("A0Plus", new Point2d(841.0, 1480.0));
            customPaperSize.Add("A0+", new Point2d(841.0, 1470.0));
            customPaperSize.Add("GBKN", new Point2d(594.0, 1051.0));

            customPaperSize.Add("4Z", new Point2d(297.0, 750.0));
            customPaperSize.Add("5Z", new Point2d(297.0, 930.0));
            customPaperSize.Add("6Z", new Point2d(297.0, 1110.0));
            customPaperSize.Add("7Z", new Point2d(297.0, 1290.0));

            customPaperSize.Add("Z3", new Point2d(297.0, 594.0));
            customPaperSize.Add("Z4", new Point2d(297.0, 841.0));
            customPaperSize.Add("Z6", new Point2d(297.0, 1189.0));

            customPaperSize.Add("3A4", new Point2d(297.0, 630.0));
            customPaperSize.Add("4A4", new Point2d(297.0, 841.0));
            customPaperSize.Add("5A4", new Point2d(297.0, 1050.0));
            customPaperSize.Add("6A4", new Point2d(297.0, 1260.0));
            customPaperSize.Add("7A4", new Point2d(297.0, 1470.0));



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

                // Get the PlotInfo from the layout
                PlotInfo plInfo = new PlotInfo();
                plInfo.Layout = theLayout.ObjectId;

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

                string devName = "DWG To PDF.pc3";  //OceTds600.pc3
                plSetVdr.SetPlotConfigurationName(np, devName, null);
                plSetVdr.RefreshLists(np);

                StringCollection canMedNames = plSetVdr.GetCanonicalMediaNameList(np);
                for (int i = 0; i < canMedNames.Count; i++)
                {
                    plSetVdr.SetCanonicalMediaName(np, canMedNames[i]);
                    plSetVdr.RefreshLists(np);
                    string medName = plSetVdr.GetLocaleMediaName(np, i);
                    //ed.WriteMessage("\n{0}: Can. MediaName={1}/{2}", i, np.CanonicalMediaName, medName);
                    if (medName.Equals("ISO A1 (841.00 x 594.00 MM)"))
                    {
                        ed.WriteMessage("\n{0}: Can. MediaName={1}/{2}", i, np.CanonicalMediaName, medName);
                        Point2d pSize = np.PlotPaperSize;
                        ed.WriteMessage("\n\tPaperSize={0}", pSize.ToString());
                        PlotRotation pRot = np.PlotRotation;
                        ed.WriteMessage("\n\tPlot Rotation={0}", pRot.ToString());
                        Extents2d pM = np.PlotPaperMargins;
                        ed.WriteMessage("\n\tPaper Margins={0}, {1}", pM.MinPoint.ToString(), pM.MaxPoint.ToString());
                    }
                }
            }
        }
Esempio n. 20
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;
        }