/// <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));
                    }
                }
            }
        }
Esempio n. 2
0
        private void comboBoxPlotAreaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            String newViewType = comboBoxPlotAreaType.SelectedItem.ToString();

            PlotType pt = PlotType.Display;

            if (newViewType != "Display")
            {
                if (newViewType == "Limits")
                {
                    pt = PlotType.Limits;
                }
                else if (newViewType == "View")
                {
                    pt = PlotType.View;
                }
                else if (newViewType == "Window")
                {
                    pt = PlotType.Window;
                }
                else if (newViewType == "Extents")
                {
                    pt = PlotType.Extents;
                }
                else if (newViewType == "Layout")
                {
                    pt = PlotType.Layout;
                }
            }

            m_plotSettingVal.SetPlotType(m_plotStg, pt);
            FillPlotAreaCombo(false);

            if (pt == PlotType.Layout)
            {
                // This is differences between dialog and validator. Validator doesn't
                // change UseStandardScale to false. Example is kExtents, kFit2Paper -> kLayout ->kExtents
                // Dialog has kFit2Paper disabled, but validator don't clear kFit2Paper flag.
                // Validator also don't change PlotOrigin to 0,0, if plotsenteres was true, but it change scale to 1:1 if fittopaper was true

                if (checkBoxCenterPlot.Enabled)
                {
                    m_plotSettingVal.SetPlotOrigin(m_plotStg, new Point2d(0, 0));
                }
                if (checkBoxPlotScaleFitToPaper.Enabled)
                {
                    m_plotSettingVal.SetUseStandardScale(m_plotStg, false);
                }
            }
            FillPaperOrientation();
            FillScaleValues(false);
            FillPlotOffset();
        }
        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. 4
0
        /// <summary>
        /// 创建布局和视口
        ///
        /// </summary>
        public static void CreateLayout(double[] B_Sta, Document doc, Database db)
        {
            //  var doc = Application.DocumentManager.MdiActiveDocument;

            if (doc == null)
            {
                return;
            }
            // var db = doc.Database;
            var ed     = doc.Editor;
            var ext    = new Extents2d();
            int k      = 0;// 100000 / 2600 / 3
            int zhushi = 0;
            //求布局数
            double Layoutnum = (B_Sta[B_Sta.Length - 1] - B_Sta[0]) / 350 / 3;

            for (int j = 0; j < Layoutnum + 1; j++)
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    //以读模式打开块表
                    BlockTable acBlkTbl;
                    acBlkTbl = tr.GetObject(db.BlockTableId,
                                            OpenMode.ForRead) as BlockTable;
                    //以写模式打开块表记录Paper空间
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.PaperSpace],
                                               OpenMode.ForWrite) as BlockTableRecord;
                    //切换到Paper空间布局
                    Application.SetSystemVariable("TILEMODE", 0);
                    doc.Editor.SwitchToPaperSpace();

                    // Create and select a new layout tab
                    var id = LayoutManager.Current.CreateAndMakeLayoutCurrent("病害处理" + j);
                    // Open the created layout
                    var lay = (Layout)tr.GetObject(id, OpenMode.ForWrite);
                    // Make some settings on the layout and get its extents

                    /*     lay.SetPlotSettings(
                     *   //  "ISO_full_bleed_2A0_(1189.00_x_1682.00_MM)", // Try this big boy!
                     *     "ANSI_B_(11.00_x_17.00_Inches)",
                     *     "monochrome.ctb",
                     *     "DWF6 ePlot.pc3");*/
                    //从布局中获取PlotInfo
                    PlotInfo acPlInfo = new PlotInfo();
                    acPlInfo.Layout = lay.ObjectId;
                    //复制布局中的PlotSettings
                    PlotSettings acPlSet = new PlotSettings(lay.ModelType);
                    acPlSet.CopyFrom(lay);
                    //更新PlotSettings对象
                    PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                    //设置打印区域
                    acPlSetVdr.SetPlotType(acPlSet,
                                           Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                    //设置打印比例
                    acPlSetVdr.SetUseStandardScale(acPlSet, true);
                    acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);
                    //居中打印
                    acPlSetVdr.SetPlotCentered(acPlSet, true);
                    ext = lay.GetMaximumExtents();
                    //绘制边框
                    //Create a polyline with two segments (3 points)
                    using (Autodesk.AutoCAD.DatabaseServices.Polyline acPoly = new Autodesk.AutoCAD.DatabaseServices.Polyline())

                    {
                        acPoly.AddVertexAt(0, new Point2d(0.2, 0.7), 0, 0, 0);
                        acPoly.AddVertexAt(1, new Point2d(0.2, ext.MaxPoint.Y - 0.3), 0, 0, 0);
                        acPoly.AddVertexAt(2, new Point2d(ext.MaxPoint.X - 0.13, ext.MaxPoint.Y - 0.3), 0, 0, 0);
                        acPoly.AddVertexAt(3, new Point2d(ext.MaxPoint.X - 0.13, 0.7), 0, 0, 0);
                        acPoly.AddVertexAt(4, new Point2d(0.2, 0.7), 0, 0, 0);
                        acPoly.LineWeight = LineWeight.LineWeight200;
                        //将新对象添加到块表记录和事务
                        acBlkTblRec.AppendEntity(acPoly);
                        tr.AddNewlyCreatedDBObject(acPoly, true);
                    }
                    //创建下方直线分隔
                    double[] Xiafangzuobiao = new double[] { 1.5, 4, 7, 7.5, 8.1, 8.6, 9.2, 9.7, 10.3, 10.8 };
                    for (int i = 0; i < Xiafangzuobiao.Length; i++)
                    {
                        WxxTU.Createline(acBlkTblRec, tr, Xiafangzuobiao[i], Xiafangzuobiao[i], 0.7, 1);
                    }
                    //创建下方需要填写的文字
                    string[] Xiafangwenzi        = new string[] { "路面病害处治设计图", "设计", "复核", "审核", "图号" };
                    double[] Xiafangwenzizuobiao = new double[] { 4.5, 7, 8.15, 9.2, 10.4 };
                    for (int i = 0; i < Xiafangwenzi.Length; i++)
                    {
                        //创建一个单行文字对象
                        using (DBText acText = new DBText())
                        {
                            acText.Position = new Point3d(Xiafangwenzizuobiao[i], 0.8, 0);
                            acText.Height   = 0.15;

                            acText.TextString = Xiafangwenzi[i];
                            acText.ColorIndex = 0;
                            //文字反向   acText.IsMirroredInX = false;
                            acText.Rotation = 0;
                            acBlkTblRec.AppendEntity(acText);
                            tr.AddNewlyCreatedDBObject(acText, true);


                            //释放DBObject对象
                        }
                    }
                    //创建上方直线分割
                    double[] Shangfangzuobiao = new double[] { 10, 10.8 };
                    for (int i = 0; i < Shangfangzuobiao.Length; i++)
                    {
                        WxxTU.Createline(acBlkTblRec, tr, Shangfangzuobiao[i], Shangfangzuobiao[i], ext.MaxPoint.Y - 0.3, ext.MaxPoint.Y - 0.65);
                    }
                    //创建上方需要填写的文字
                    string[] Shangfangwenzi = new string[] { "第" + j + "页", "共" + Math.Truncate(Layoutnum) + "页" };
                    for (int i = 0; i < Shangfangwenzi.Length; i++)
                    {
                        //创建一个单行文字对象
                        using (DBText acText = new DBText())
                        {
                            acText.Position = new Point3d(Shangfangzuobiao[i], ext.MaxPoint.Y - 0.5, 0);
                            acText.Height   = 0.15;

                            acText.TextString = Shangfangwenzi[i];
                            acText.ColorIndex = 0;
                            //文字反向   acText.IsMirroredInX = false;
                            acText.Rotation = 0;
                            acBlkTblRec.AppendEntity(acText);
                            tr.AddNewlyCreatedDBObject(acText, true);


                            //释放DBObject对象
                        }
                    }
                    //创建桩号起终点注释
                    double[] Sta_Y = new double[] { 2.75, 5, 7.1 };
                    for (int i = 0; i < 3; i++)
                    {
                        using (DBText acText = new DBText())
                        {
                            acText.Position = new Point3d(9, Sta_Y[i], 0);
                            acText.Height   = 0.15;

                            acText.TextString = WxxTU.Station_Double2Str(B_Sta[0] + 350 * (zhushi - 3)) + "-" + WxxTU.Station_Double2Str(B_Sta[0] + 350 * (zhushi - 2));
                            acText.ColorIndex = 0;
                            //文字反向   acText.IsMirroredInX = false;
                            acText.Rotation = 0;
                            acBlkTblRec.AppendEntity(acText);
                            tr.AddNewlyCreatedDBObject(acText, true);
                            zhushi++;

                            //释放DBObject对象
                        }
                    }

                    //创建多个视口
                    for (int i = 0; i < 3; i++)
                    {
                        lay.ApplyToViewport(
                            tr, i,
                            vp =>
                        {
                            // Size the viewport according to the extents calculated when
                            // we set the PlotSettings (device, page size, etc.)
                            // Use the standard 10% margin around the viewport
                            // (found by measuring pixels on screenshots of Layout1, etc.)

                            vp.ResizeViewport(ext, 0.8, 2 * i + 1, k);
                            k++;

                            /* // Adjust the view so that the model contents fit
                             * if (ValidDbExtents(db.Extmin, db.Extmax))
                             * {
                             *   vp.FitContentToViewport(new Extents3d(db.Extmin, db.Extmax),0.8);
                             * }
                             *
                             * // Finally we lock the view to prevent meddling*/


                            vp.Locked = true;
                        }
                            );
                    }
                    //  k++;

                    // Commit the transaction
                    tr.Commit();
                }
            }
            // Zoom so that we can see our new layout, again with a little padding

            /*    ed.Command("_.ZOOM", "_E");
             *  ed.Command("_.ZOOM", ".7X");
             *  ed.Regen();*/
        }
Esempio n. 5
0
        static public void PublishViews2MultiSheet()
        {
            pwdWindow = new PasswordWindow();
            pwdWindow.ShowDialog();
            Document         doc         = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database         db          = doc.Database;
            Editor           ed          = doc.Editor;
            StringCollection viewsToPlot = new StringCollection();

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

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

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

                /*DsdFile */
                string dsdFile = dsdData.ProjectPath + dwgFileName + ".dsd";
                dsdData.WriteDsd(dsdFile);
                System.IO.StreamReader sr = new System.IO.StreamReader(dsdFile);
                string str = sr.ReadToEnd();
                sr.Close();
                str = str.Replace("PromptForDwfName=TRUE",
                                  "PromptForDwfName=FALSE");
                /*Prompts User to Enter Password and Reconfirms*/
                //str = str.Replace("PromptForPwd=FALSE",
                //                   "PromptForPwd=TRUE");
                //str = str.Replace("PwdProtectPublishedDWF=FALSE",
                //                   "PwdProtectPublishedDWF=TRUE");
                int           occ        = 0;
                int           index      = str.IndexOf("Setup=");
                int           startIndex = 0;
                StringBuilder dsdText    = new StringBuilder();
                while (index != -1)
                {
                    String str1 = str.Substring(startIndex, index + 6 - startIndex);
                    dsdText.Append(str1);
                    dsdText.Append(String.Format("{0}{1}", viewsToPlot[occ], "PS"));
                    startIndex = index + 6;
                    index      = str.IndexOf("Setup=", index + 6);
                    if (index == -1)
                    {
                        dsdText.Append(str.Substring(startIndex, str.Length - startIndex));
                    }
                    occ++;
                }
                System.IO.StreamWriter sw = new System.IO.StreamWriter(dsdFile);
                sw.Write(dsdText.ToString());
                sw.Close();
                dsdData.ReadDsd(dsdFile);
                System.IO.File.Delete(dsdFile);
                PlotConfig plotConfig = PlotConfigManager.SetCurrentConfig("DWF6 ePlot.pc3");
                Publisher  publisher  = Autodesk.AutoCAD.ApplicationServices.Core.Application.Publisher;
                publisher.PublishExecute(dsdData, plotConfig);
                Tx.Commit();
            }
            Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);
        }
Esempio n. 6
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. 7
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. 8
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. 9
0
        //打印模型布局的范围
        //打印到DWF文件

        //[CommandMethod("PlotCurrentLayout")]
        /// <summary>
        /// 打印输出单个文件
        /// </summary>
        /// <param name="LayerName"></param>
        /// <param name="FileName"></param>
        /// <param name="outputFilePath"></param>
        /// <param name="printer"></param>
        /// <param name="paperFormat"></param>
        public static void PlotCurrentLayout(string LayerName, string FileName, string outputFilePath, string printer, string paperFormat)
        {
            // 获取当前文档和数据库,启动事务
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 获取图层
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;

                // 将活动图层修改为第一个,即图层0
                acCurDb.Clayer = acLyrTbl[LayerName];
                LayerTableRecord acLayerTblRec = acTrans.GetObject(acLyrTbl[LayerName], OpenMode.ForWrite) as LayerTableRecord;
                acLayerTblRec.IsOff = false; //显示该图层

                // 引用布局管理器LayoutManager
                LayoutManager acLayoutMgr;
                acLayoutMgr = LayoutManager.Current;

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

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

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

                // 更新PlotSettings对象
                PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;

                //// 获取打印设备
                //StringCollection deviceList = acPlSetVdr.GetPlotDeviceList();

                //// 打印设备列表-MessageBox形式
                //foreach (string d in deviceList)
                //{
                //    ed.WriteMessage("打印设备:" + d + "\n");
                //}

                //// 获取纸张列表
                //StringCollection mediaList = acPlSetVdr.GetCanonicalMediaNameList(acPlSet);

                //ed.WriteMessage("图纸种类:" + Convert.ToString(mediaList.Count) + " 个\n");
                //foreach (string m in mediaList)
                //{
                //    ed.WriteMessage("打印图纸:" + m + "\n");
                //}

                // 设置打印区域
                acPlSetVdr.SetPlotType(acPlSet,
                                       Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);

                // 设置打印比例
                acPlSetVdr.SetUseStandardScale(acPlSet, true);
                acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                // 居中打印
                acPlSetVdr.SetPlotCentered(acPlSet, true);

                // 设置使用的打印设备
                //acPlSetVdr.SetPlotConfigurationName(acPlSet, "PostScript Level 2.pc3",
                //"ANSI_A_(8.50_x_11.00_Inches)");
                //设置采用的打印设备与纸张格式
                acPlSetVdr.SetPlotConfigurationName(acPlSet, printer,
                                                    paperFormat);


                // 用上述设置信息覆盖PlotInfo对象,
                // 不会将修改保存回布局
                acPlInfo.OverrideSettings = acPlSet;

                // 验证打印信息
                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                acPlInfoVdr.Validate(acPlInfo);

                // 检查是否有正在处理的打印任务
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (PlotEngine acPlEng = PlotFactory.CreatePublishEngine())
                    {
                        // 使用PlotProgressDialog对话框跟踪打印进度
                        PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false,
                                                                                1,
                                                                                true);

                        using (acPlProgDlg)
                        {
                            // 定义打印开始时显示的状态信息
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle,
                                                          "Plot Progress");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage,
                                                          "Cancel Job");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage,
                                                          "Cancel Sheet");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption,
                                                          "Sheet Set Progress");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption,
                                                          "Sheet Progress");

                            // 设置打印进度范围
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;

                            // 显示打印进度对话框
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;

                            // 开始打印
                            acPlEng.BeginPlot(acPlProgDlg, null);

                            string opFile = outputFilePath + LayerName;
                            // 定义打印输出
                            acPlEng.BeginDocument(acPlInfo,
                                                  acDoc.Name,
                                                  null,
                                                  1,
                                                  true,
                                                  opFile);

                            // 显示当前打印任务的有关信息
                            //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status,
                            //                              "Plotting: " + acDoc.Name + " - " +
                            //                              acLayout.LayoutName);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status,
                                                          "Plotting: " + acDoc.Name + " - " +
                                                          LayerName);

                            // 设置图纸进度范围
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;

                            // 打印第一张图/布局
                            PlotPageInfo acPlPageInfo = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo,
                                              acPlInfo,
                                              true,
                                              null);

                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);

                            // 结束第一张图/布局的打印
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();

                            // 结束文档局的打印
                            acPlEng.EndDocument(null);

                            // 打印结束
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                        }
                    }
                }


                acLayerTblRec.IsOff = true; //关闭该图层
                printFlag           = true;
                //ed.WriteMessage("打印完成 \n");
            }
        }
Esempio n. 10
0
        public void WindowPlot()

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

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

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

                foreach (var ltrId in lt)

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

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

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

                tr.Commit();
            }


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        string FileName = name;

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

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

                    ResultBuffer rbFrom =

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

                                 rbTo =

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

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

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

                    BlockTableRecord btr =

                        (BlockTableRecord)tr.GetObject(

                            db.CurrentSpaceId,

                            OpenMode.ForRead

                            );

                    Layout lo =

                        (Layout)tr.GetObject(

                            btr.LayoutId,

                            OpenMode.ForRead

                            );
                    PlotInfo pi = new PlotInfo();

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

                    ps.CopyFrom(lo);

                    PlotSettingsValidator psv = PlotSettingsValidator.Current;

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

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

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

                    PlotInfoValidator piv =

                        new PlotInfoValidator();

                    piv.MediaMatchingPolicy =

                        MatchingPolicy.MatchEnabled;

                    piv.Validate(pi);

                    if (PlotFactory.ProcessPlotState ==

                        ProcessPlotState.NotPlotting)

                    {
                        PlotEngine pe =

                            PlotFactory.CreatePublishEngine();

                        using (pe)

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


                            PlotProgressDialog ppd =

                                new PlotProgressDialog(false, 1, true);

                            using (ppd)

                            {
                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.DialogTitle,

                                    "Custom Plot Progress"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.CancelJobButtonMessage,

                                    "Cancel Job"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.CancelSheetButtonMessage,

                                    "Cancel Sheet"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.SheetSetProgressCaption,

                                    "Sheet Set Progress"

                                    );

                                ppd.set_PlotMsgString(

                                    PlotMessageIndex.SheetProgressCaption,

                                    "Sheet Progress"

                                    );

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

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

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

                                pe.BeginDocument(

                                    pi,

                                    doc.Name,

                                    null,

                                    1,

                                    true,

                                    PDFname

                                    );

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

                                PlotPageInfo ppi = new PlotPageInfo();

                                pe.BeginPage(

                                    ppi,

                                    pi,

                                    true,

                                    null

                                    );

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

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

                                pe.EndDocument(null);

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

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

                    else

                    {
                        ed.WriteMessage(

                            "\nAnother plot is in progress."

                            );
                    }
                }
            }

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

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

                foreach (var ltrId in lt)

                {
                    bool lockZero = false;

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

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

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

                tr.Commit();
            }
        }
Esempio n. 11
0
        public void PrintTT()
        {
            Document      acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb   = acDoc.Database;
            Editor        ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            List <String> imagelist = new List <String>();

            string directory = @"D:\";//磁盘路径
            string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels");

            try
            {
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        int flag = 0;
                        //获取当前布局管理器变量
                        LayoutManager acLayoutMgr = LayoutManager.Current;
                        //获取当前布局变量
                        Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead);
                        //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite);
                        //获取当前布局的打印信息
                        PlotInfo acPlInfo = new PlotInfo()
                        {
                            Layout = acLayout.ObjectId
                        };



                        //提示用户输入打印窗口的两个角点
                        PromptPointResult resultp = ed.GetPoint("\n指定第一个角点");
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d basePt = resultp.Value;
                        resultp = ed.GetCorner("指定对角点", basePt);
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d cornerPt = resultp.Value;

                        //选择实体对象
                        // PromptSelectionOptions result1 = new PromptSelectionOptions();

                        SelectionFilter frameFilter = new SelectionFilter(
                            new TypedValue[]
                            { new TypedValue(0, "LWPOLYLINE"),
                              new TypedValue(90, 4),
                              new TypedValue(70, 1) });


                        PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter);
                        // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter);
                        PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter);
                        if (selectedFrameResult.Status == PromptStatus.OK)
                        {
                            List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            List <ObjectId> resultObjectIds   = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds);
                            foreach (ObjectId frameId in resultObjectIds)
                            {
                                Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline;
                                framePline.Highlight();
                            }


                            PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                            acPlSet.CopyFrom(acLayout);
                            //着色打印选项,设置按线框进行打印
                            acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe;
                            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                            //打印比例
                            //用户标准打印
                            acPlSetVdr.SetUseStandardScale(acPlSet, true);
                            acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                            //居中打印
                            acPlSetVdr.SetPlotCentered(acPlSet, true);
                            //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet
                            System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList();
                            //设置打印样式表
                            if (comboBoxStyleSheet.SelectedItem.ToString() == "无")
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb");
                            }

                            else
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString());
                            }

                            //选择方向
                            if (radioButtonHorizontal.Checked)
                            {
                                //横向
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                            }

                            //竖向
                            if (radioButtonVertical.Checked)
                            {
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                            }
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true);
                            string             imagename   = "";
                            string[]           files       = new string[] { };
                            List <string>      listfile    = new List <string>();
                            foreach (var frame in resultObjectIds)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }
                                flag++;

                                Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity;

                                imagename = string.Format("{0}-{1}.pdf", frame, flag);
                                //imagelist.Add(directory + imagename);
                                listfile.Add(directory + imagename);


                                //设置是否使用打印样式
                                acPlSet.ShowPlotStyles = true;
                                //设置打印区域
                                Extents3d extents3d = ent.GeometricExtents;

                                Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y);
                                acPlSetVdr.SetPlotWindowArea(acPlSet, E2d);
                                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                //重载和保存打印信息
                                acPlInfo.OverrideSettings = acPlSet;
                                //验证打印信息设置,看是否有误
                                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                acPlInfoVdr.Validate(acPlInfo);

                                while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                                {
                                    continue;
                                }
                                #region BackUpCode

                                //保存App的原参数
                                short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                                //设定为前台打印,加快打印速度
                                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                                PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine();
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                                //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                acPlEng1.BeginPlot(acPlProgDlg, null);
                                acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                                //  acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng1.BeginGenerateGraphics(null);
                                acPlEng1.EndGenerateGraphics(null);
                                acPlEng1.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                acPlEng1.EndDocument(null);
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng1.EndPlot(null);
                                acPlEng1.Dispose();
                                acPlEng1.Destroy();
                                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);

                                #endregion
                            }


                            files = listfile.ToArray();
                            PlotConfig config = PlotConfigManager.CurrentConfig;
                            //获取去除扩展名后的文件名(不含路径)
                            string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg");
                            //定义保存文件对话框
                            PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名")
                            {
                                //保存文件对话框的文件扩展名列表
                                Filter           = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension,
                                DialogCaption    = "浏览打印文件",                            //保存文件对话框的标题
                                InitialDirectory = @"D:\",                              //缺省保存目录
                                InitialFileName  = fileName + "-" + acLayout.LayoutName //缺省保存文件名
                            };
                            //根据保存对话框中用户的选择,获取保存文件名
                            PromptFileNameResult result = ed.GetFileNameForSave(opt);
                            if (result.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            fileName = result.StringResult;

                            //string fileName = @"D:\输出.pdf";
                            PdfDocumentBase docx = PdfDocument.MergeFiles(files);
                            docx.Save(fileName, FileFormat.PDF);
                            System.Diagnostics.Process.Start(fileName);



                            //保存App的原参数
                            short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                            //设定为前台打印,加快打印速度
                            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                            PlotEngine acPlEng = PlotFactory.CreatePublishEngine();
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;
                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;
                            PlotPageInfo acPlPageInfo1 = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null);
                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();
                            acPlEng.EndDocument(null);
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                            acPlEng.Dispose();
                            acPlEng.Destroy();
                            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1);

                            acPlProgDlg.Dispose();
                            acPlProgDlg.Destroy();

                            for (int i = 0; i < files.Length; i++)
                            {
                                File.Delete(files[i]);
                            }
                        }
                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            continue;
                        }
                        //MessageBox.Show("打印完成!");
                    }
                }
                else
                {
                    ed.WriteMessage("\n另一个打印进程正在进行中.");
                }
            }



            catch (System.Exception)
            {
                throw;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// plotting method
        /// </summary>
        /// <param name="pdfFileName"> name</param>
        /// <param name="printModel">print param model</param>
        public static void PlotCurrentLayout(string pdfFileName, PrintModel printModel)
        {
            // Get the current document and database, and start a transaction
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

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

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

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

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

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

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

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

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

                    // Set the plot device to use

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

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

                                acPlEng.BeginDocument(acPlInfo, acDoc.Name, null, 1, true, filename);
                                // Display information about the current plot
                                acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status,
                                                              "Plotting: " + acDoc.Name + " - " + acLayout.LayoutName);
                                // Set the sheet progress range
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                // Plot the first sheet/layout
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng.BeginGenerateGraphics(null);
                                acPlEng.EndGenerateGraphics(null);
                                // Finish plotting the sheet/layout
                                acPlEng.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                // Finish plotting the document
                                acPlEng.EndDocument(null);
                                // Finish the plot
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng.EndPlot(null);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Application.ShowAlertDialog(e.Message);
            }
        }
Esempio n. 13
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. 14
0
        public void SetLayoutPlotSetting()
        {
            Document       acDoc          = Application.DocumentManager.MdiActiveDocument;
            Database       acCurDb        = acDoc.Database;
            StandartCopier standartCopier = new StandartCopier();

            PlotConfigManager.SetCurrentConfig(standartCopier.Pc3Location);

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Layout acLayout;

                LayoutModels = LayoutModels.OrderBy(x => x.Layout.TabOrder).ToList();

                foreach (var layout in LayoutModels)
                {
                    acLayout = acTrans.GetObject(layout.LayoutPlotId,
                                                 OpenMode.ForRead) as Layout;

                    if (acLayout == null)
                    {
                        continue;
                    }

                    LayoutManager lm = LayoutManager.Current;
                    lm.CurrentLayout = acLayout.LayoutName;

                    var plotArea = acLayout.Extents;
                    // Output the name of the current layout and its device
                    acDoc.Editor.WriteMessage("\nCurrent layout: " +
                                              acLayout.LayoutName);

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

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

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

                    // Update the PlotConfigurationName property of the PlotSettings object
                    PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                    //acPlSetVdr.SetCurrentStyleSheet(acPlSet, "monochrome.ctb");
                    bool isHor = layout.PrintModel.IsFormatHorizontal();

                    acPlSetVdr.SetPlotType(acPlSet, PlotType.Extents);
                    acPlSetVdr.SetPlotRotation(acPlSet, isHor ? PlotRotation.Degrees000 : PlotRotation.Degrees090);
                    acPlSetVdr.SetPlotWindowArea(acPlSet, Get2dExtentsFrom3d(plotArea));
                    acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                    // Center the plot
                    acPlSetVdr.SetPlotCentered(acPlSet, true);

                    acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG_To_PDF_Uzle.pc3",
                                                        layout.CanonicalName);
                    acPlSetVdr.SetZoomToPaperOnUpdate(acPlSet, true);
                    // Update the layout
                    acLayout.UpgradeOpen();
                    acLayout.CopyFrom(acPlSet);

                    // Output the name of the new device assigned to the layout
                    acDoc.Editor.WriteMessage("\nNew device name: " +
                                              acLayout.PlotConfigurationName);

                    Active.Editor.Regen();
                }

                // Save the new objects to the database
                acTrans.Commit();
            }
        }
Esempio n. 15
0
        public static void ChangePlotSetting(string borderSize)
        {
            string      mediaName;
            CustomScale cmScale;

            switch (borderSize)
            {
            case "AE":
                mediaName = "ARCH_E1_(30.00_x_42.00_Inches)";
                cmScale   = new CustomScale(1, 1.037);
                break;

            case "B":
                mediaName = "ANSI_expand_B_(11.00_x_17.00_Inches)";
                cmScale   = new CustomScale(1, 1.037);
                break;

            case "C":
                mediaName = "ARCH_expand_C_(18.00_x_24.00_Inches)";
                cmScale   = new CustomScale(1, 1.037);
                break;

            case "D":
                mediaName = "ARCH_expand_D_(24.00_x_36.00_Inches)";
                cmScale   = new CustomScale(1, 1);
                break;

            case "E":
                mediaName = "ARCH_E_(36.00_x_48.00_Inches)";
                cmScale   = new CustomScale(1, 1.032);
                break;

            case "F":
                mediaName = "ARCH_E1_(30.00_x_42.00_Inches)";
                cmScale   = new CustomScale(1, 1.037);
                break;

            default:
                mediaName = "ARCH_expand_D_(24.00_x_36.00_Inches)";
                cmScale   = new CustomScale(1, 1);
                break;
            }

            // Get the current document and database, and start a transaction
            Document acDoc   = Acad.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Reference the Layout Manager
                var acLayoutMgr = LayoutManager.Current;

                // Get the current layout and output its name in the Command Line window
                var acLayout = acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout),
                                                 OpenMode.ForRead) as Layout;

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

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

                    // Update the PlotConfigurationName property of the PlotSettings object
                    PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                    acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWF6 ePlot.pc3", mediaName);
                    acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);

                    acPlSetVdr.SetPlotCentered(acPlSet, true);
                    acPlSetVdr.SetCustomPrintScale(acPlSet, cmScale);


                    // Update the layout
                    acLayout.UpgradeOpen();
                    acLayout.CopyFrom(acPlSet);

                    // Output the name of the new device assigned to the layout
                    acDoc.Editor.WriteMessage("\nNew device name: " + acLayout.PlotConfigurationName);
                }

                //regen the current view
                Acad.DocumentManager.MdiActiveDocument.Editor.Regen();

                //zoom to the extents of the drawing
                acDoc.SendStringToExecute("._zoom _all ", true, false, false);

                // Save the new objects to the database
                acTrans.Commit();
            }
        }
Esempio n. 16
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. 17
0
        static public void MultiSheetPlot(Document doc, DirectoryInfo diPDF, string panelName)
        {
            Editor   ed = doc.Editor;
            Database db = doc.Database;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                PlotInfo          pi  = new PlotInfo();
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;

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

                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    PlotEngine pe = PlotFactory.CreatePublishEngine();
                    using (pe)
                    {
                        // Collect all the paperspace layouts for plotting
                        ObjectIdCollection      layoutsToPlot     = new ObjectIdCollection();
                        List <BlockTableRecord> btrListToBeSorted = new List <BlockTableRecord>();

                        foreach (ObjectId btrId in bt)
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);

                            if (btr.IsLayout && btr.Name.ToUpper() != BlockTableRecord.ModelSpace.ToUpper())
                            {
                                layoutsToPlot.Add(btrId);
                            }
                        }

                        //Sort the layout by name
                        btrListToBeSorted.Sort((x, y) => string.Compare(x.Name, y.Name));

                        foreach (BlockTableRecord btr in btrListToBeSorted)
                        {
                            layoutsToPlot.Add(btr.Id);
                        }

                        // Create a Progress Dialog to provide info and allow thej user to cancel
                        PlotProgressDialog ppd = new PlotProgressDialog(false, layoutsToPlot.Count, true);

                        using (ppd)
                        {
                            int numSheet = 1;

                            foreach (ObjectId btrId in layoutsToPlot)
                            {
                                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForWrite);
                                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;

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


                                // We'll use the standard PDF, as this supports multiple sheets
                                //Think about changing the DWG To PDF settings to custom value for setting up printing margin
                                //psv.SetPlotConfigurationName(ps,"DWFx ePlot (XPS Compatible).pc3", "ANSI_A_(8.50_x_11.00_Inches)");
                                //psv.SetPlotConfigurationName(ps, "DWG To PDF_Custom.pc3", "ISO_A4_(210.00_x_297.00_MM)");
                                psv.SetPlotConfigurationName(ps, "DWG To PDF_Custom.pc3", "ISO_expand_A4_(210.00_x_297.00_MM)");

                                // We need a PlotInfo object linked to the layout

                                pi.Layout = btr.LayoutId;

                                // Make the layout we're plotting current
                                LayoutManager.Current.CurrentLayout = lo.LayoutName;

                                //Change the name in it
                                ACADFunction.ChangeName(doc, panelName);

                                foreach (ObjectId vpId in lo.GetViewports())
                                {
                                    Viewport vp = (Viewport)tr.GetObject(vpId, OpenMode.ForWrite);
                                    vp.StandardScale = StandardScaleType.ScaleToFit;
                                    //vp.CustomScale = 10;
                                }

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

                                pi.OverrideSettings = ps;
                                piv.Validate(pi);

                                if (numSheet == 1)
                                {
                                    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
                                    // Let's plot to file
                                    pe.BeginDocument(pi, doc.Name, null, 1, true, diPDF.FullName + @"\" + panelName + ".pdf");
                                }

                                // Which may contain multiple sheets

                                ppd.StatusMsgString = "Plotting " + doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1) + " - sheet " + numSheet.ToString() + " of " + layoutsToPlot.Count.ToString();

                                ppd.OnBeginSheet();

                                ppd.LowerSheetProgressRange = 0;
                                ppd.UpperSheetProgressRange = 100;
                                ppd.SheetProgressPos        = 0;

                                PlotPageInfo ppi = new PlotPageInfo();
                                pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null);
                                pe.BeginGenerateGraphics(null);
                                ppd.SheetProgressPos = 50;
                                pe.EndGenerateGraphics(null);

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

                            // Finish the document

                            pe.EndDocument(null);

                            // And finish the plot

                            ppd.PlotProgressPos = 100;
                            ppd.OnEndPlot();
                            pe.EndPlot(null);
                        }
                    }
                }
                else
                {
                    ed.WriteMessage(
                        "\nAnother plot is in progress."
                        );
                }

                tr.Commit();
            }
        }
Esempio n. 18
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. 19
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;
        }