Esempio n. 1
0
        private void PublisherDSD(DsdEntryCollection collection)
        {
            var dsdFile  = Path.Combine(dir, filePdfOutputName + ".dsd");
            var destFile = Path.Combine(dir, filePdfOutputName + ".pdf");

            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
            using (var dsd = new DsdData())
            {
                dsd.SetDsdEntryCollection(collection);
                dsd.SheetType        = SheetType.MultiPdf;
                dsd.IsSheetSet       = true;
                dsd.NoOfCopies       = 1;
                dsd.IsHomogeneous    = false;
                dsd.DestinationName  = destFile;
                dsd.SheetSetName     = "PublisherSet";
                dsd.PromptForDwfName = false;
                PostProcessDSD(dsd, dsdFile);
            }

            using (var progressDlg = new PlotProgressDialog(false, collection.Count, true))
            {
                progressDlg.IsVisible = true;
                var publisher = Application.Publisher;
                PlotConfigManager.SetCurrentConfig("clk-PDF.pc3");
                publisher.PublishDsd(dsdFile, progressDlg);
                progressDlg.Destroy();
            }
        }
Esempio n. 2
0
        public void UpdatePaperListbox(ComboBox aCmbPlotDevice, ComboBox aCmbPaperSize, string aDeviceName)
        {
            aCmbPaperSize.Items.Clear();

            if (aCmbPlotDevice.Text == "None" || string.IsNullOrEmpty(aCmbPlotDevice.Text))
            {
                return;
            }

            try
            {
                PlotConfig pc = PlotConfigManager.SetCurrentConfig(aDeviceName);
                if (pc.IsPlotToFile || pc.PlotToFileCapability == PlotToFileCapability.MustPlotToFile || pc.PlotToFileCapability == PlotToFileCapability.PlotToFileAllowed)
                {
                    aCmbPaperSize.Items.Add("Auto");
                }

                foreach (string str in pc.CanonicalMediaNames)
                {
                    if (CanonicalMediaNamesFilter.IsMatch(str))
                    {
#if !bcad
                        aCmbPaperSize.Items.Add(pc.GetLocalMediaName(str));
#else
                        aCmbPaperSize.Items.Add(str);
#endif
                    }
                }
                aCmbPaperSize.Text = aCmbPaperSize.Items[0].ToString();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace);
            }
        }
Esempio n. 3
0
        public void PublishPackage(PrintPackageModel package)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");

            Application.SetSystemVariable("BACKGROUNDPLOT", 0);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DsdEntryCollection collection = new DsdEntryCollection();
                foreach (var layoutModel in package.Layouts)
                {
                    DsdEntry entry = new DsdEntry();
                    entry.DwgName      = package.DwgPath + package.DwgFileName;
                    entry.Layout       = layoutModel.LayoutName;
                    entry.Title        = "Layout_" + layoutModel.LayoutName;
                    entry.NpsSourceDwg = entry.DwgName;
                    entry.Nps          = "Setup1";

                    collection.Add(entry);
                }

                DsdData dsdData = new DsdData();
                dsdData.SheetType       = SheetType.MultiPdf; //SheetType.MultiPdf
                dsdData.ProjectPath     = package.DwgPath;
                dsdData.DestinationName =
                    $"{dsdData.ProjectPath}{package.PdfFileName}.pdf";
                if (System.IO.File.Exists(dsdData.DestinationName))
                {
                    System.IO.File.Delete(dsdData.DestinationName);
                }
                dsdData.SetDsdEntryCollection(collection);
                string dsdFile = $"{dsdData.ProjectPath}{package.PdfFileName}.dsd";

                dsdData.WriteDsd(dsdFile);
                dsdData.ReadDsd(dsdFile);

                System.IO.File.Delete(dsdFile);
                var plotConfig = PlotConfigManager.SetCurrentConfig("DWG_To_PDF_Uzle.pc3");
                var publisher  = Application.Publisher;

                publisher.AboutToBeginPublishing +=
                    new Autodesk.AutoCAD.Publishing.
                    AboutToBeginPublishingEventHandler(
                        Publisher_AboutToBeginPublishing);
                dsdData.PromptForDwfName = false;
                publisher.PublishExecute(dsdData, plotConfig);
                tr.Commit();
            }

            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);
        }
Esempio n. 4
0
        public void Test()
        {
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            var Text   = new List <string>();
            var editor = Acad.DocumentManager.MdiActiveDocument.Editor;

            System.Collections.Specialized.StringCollection vs = psv.GetPlotDeviceList();
            foreach (var st in vs)
            {
                editor.WriteMessage(st.ToString() + Environment.NewLine);
                Text.Add(st.ToString());
            }
            using (PlotSettings ps = new PlotSettings(false))
            {
                foreach (var st in vs)
                {
                    editor.WriteMessage("Текущий/Selected: " + st.ToString() + Environment.NewLine);
                    Text.Add("Текущий/Selected: " + st.ToString());
                    if (st.ToString() == "AutoCAD PDF (High Quality Print).pc3")
                    {
                        PlotConfig config = PlotConfigManager.SetCurrentConfig(st.ToString());
                        PlotInfo   info   = new PlotInfo();
                        psv.SetPlotConfigurationName(ps, st.ToString(), null);
                        psv.RefreshLists(ps);
                        System.Collections.Specialized.StringCollection mediaName = psv.GetCanonicalMediaNameList(ps);
                        foreach (var media in mediaName)
                        {
                            editor.WriteMessage("Формат/Media name " + media.ToString() + Environment.NewLine);
                            Text.Add("Формат/Media name " + media.ToString());
                            MediaBounds bounds = config.GetMediaBounds(media.ToString());
                            editor.WriteMessage(Math.Round(bounds.PageSize.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.PageSize.Y).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.Y).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.X).ToString() + Environment.NewLine);
                            editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString() + Environment.NewLine);
                            Text.Add(Math.Round(bounds.PageSize.X).ToString());
                            Text.Add(Math.Round(bounds.PageSize.Y).ToString());
                            Text.Add(Math.Round(bounds.LowerLeftPrintableArea.X).ToString());
                            Text.Add(Math.Round(bounds.UpperRightPrintableArea.Y).ToString());
                            Text.Add(Math.Round(bounds.UpperRightPrintableArea.X).ToString());
                            Text.Add(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString());
                        }
                    }
                }
            }
            System.IO.File.WriteAllLines("C:\\users\\dyn1\\desktop\\info.txt", Text);
        }
Esempio n. 5
0
        //public Extents2d Extents3dToExtents2d()
        //{
        //Extents3d point3d = this.BlockPoint3d;

        //Point3d minPoint3dWcs =
        //    new Point3d(this.BlockPoint3d.MinPoint[0], point3d.MinPoint[1], point3d.MinPoint[2]);
        //Point3d minPoint3d = Autodesk.AutoCAD.Internal.Utils.UcsToDisplay(minPoint3dWcs, false);
        //Point3d maxPoint3dWcs = new Point3d(point3d.MaxPoint[0], point3d.MaxPoint[1], point3d.MaxPoint[2]);
        //Point3d maxPoint3d = Autodesk.AutoCAD.Internal.Utils.UcsToDisplay(maxPoint3dWcs, false);
        //Extents2d points = new Extents2d(new Point2d(minPoint3d[0], minPoint3d[1]),
        //    new Point2d(maxPoint3d[0], maxPoint3d[1]));

        //return points;
        //}


        //public bool IsFormatHorizontal()
        //{
        //    double minPointX = BlockPoint3d.MinPoint[0];
        //    double minPointY = BlockPoint3d.MinPoint[1];

        //    double maxPointX = BlockPoint3d.MaxPoint[0];
        //    double maxPointY = BlockPoint3d.MaxPoint[1];

        //    this.Width = maxPointX - minPointX;
        //    this.Height = maxPointY - minPointY;

        //    if (Height > Width) return false;

        //    return true;
        //}

        private static string GetLocalNameByAtrrValue(string attrvalue = "А3")
        {
            StandartCopier standartCopier = new StandartCopier();
            PlotConfig     pConfig        = PlotConfigManager.SetCurrentConfig(standartCopier.Pc3Location);
            string         canonName      = "";

            foreach (var canonicalMediaName in pConfig.CanonicalMediaNames)
            {
                string localName = pConfig.GetLocalMediaName(canonicalMediaName);
                if (localName == attrvalue)
                {
                    canonName = canonicalMediaName;
                }

                Active.Editor.WriteMessage("\n" + canonicalMediaName);
            }

            return(canonName);
        }
Esempio n. 6
0
        public string GetCanonNameByExtents()
        {
            StandartCopier standartCopier = new StandartCopier();
            PlotConfig     pConfig        = PlotConfigManager.SetCurrentConfig(standartCopier.Pc3Location);

            string pat = @"\d{1,}?\.\d{2}";

            //double width = this.Width;
            //double height = this.Height;

            string canonName = "";

            foreach (var line in pConfig.CanonicalMediaNames)
            {
                Regex pattern = new Regex(pat, RegexOptions.Compiled |
                                          RegexOptions.Singleline);
                //string str2 = Regex.Split(str, pattern);
                if (pattern.IsMatch(line))
                {
                    MatchCollection str2 = pattern.Matches(line, 0);

                    string strWidth   = str2[0].ToString();
                    string strheight  = str2[1].ToString();
                    double strWidthD  = Convert.ToDouble(strWidth, System.Globalization.CultureInfo.InvariantCulture);
                    double strheightD = Convert.ToDouble(strheight, System.Globalization.CultureInfo.InvariantCulture);

                    Console.WriteLine(strWidthD);

                    //double strheight = Convert.ToDouble(str2[1]);

                    if (strWidthD == this.Width & strheightD == this.Height)
                    {
                        Console.WriteLine("{0} ширина {1}-{2}  высота {3}-{4}", line, strWidthD, this, strheightD,
                                          this.Height);
                        canonName = line;
                        break;
                    }
                }
            }
            return(canonName);
        }
Esempio n. 7
0
        public string GetCanonNameByWidthAndHeight()
        {
            StandartCopier standartCopier = new StandartCopier();
            PlotConfig     pConfig        = PlotConfigManager.SetCurrentConfig(standartCopier.Pc3Location);

            //паттерн для размера листов
            string pat = @"\d{1,}?\.\d{2}";

            string canonName = "";

            foreach (var line in pConfig.CanonicalMediaNames)
            {
                Regex pattern = new Regex(pat, RegexOptions.Compiled |
                                          RegexOptions.Singleline);
                if (pattern.IsMatch(line))
                {
                    var    items = DivideStringToWidthAndHeight(pattern, line);
                    double curWidth;
                    double curHeight;

                    if (IsFormatHorizontal())
                    {
                        curWidth  = Math.Round(Width / ScaleX);
                        curHeight = Math.Round(Height / ScaleX);
                    }
                    else
                    {
                        curWidth  = Math.Round(Height / ScaleX);
                        curHeight = Math.Round(Width / ScaleX);
                    }

                    if (items.Item1 == curWidth & items.Item2 == curHeight)
                    {
                        canonName = line;
                        break;
                    }
                }
            }
            return(canonName);
        }
Esempio n. 8
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. 9
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. 10
0
        public void PublisherDSD(DsdEntryCollection collection)
        {
            try
            {
                var dsdFile = Path.Combine(dir, filePdfOutputName + ".dsd");
                if (!filePdfOutputName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
                {
                    filePdfOutputName += ".pdf";
                }
                var destFile = Path.Combine(dir, filePdfOutputName);
                CheckFileAccess(destFile);
                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                using (var dsd = new DsdData())
                {
                    if (PikSettings.UserGroup == "ДО")
                    {
                        dsd.PlotStampOn = true;
                        dsd.ProjectPath = dir;
                    }

                    dsd.SetDsdEntryCollection(collection);
                    dsd.LogFilePath      = Path.Combine(dir, "logPlotPdf.log");
                    dsd.SheetType        = SheetType.MultiPdf;
                    dsd.IsSheetSet       = true;
                    dsd.NoOfCopies       = 1;
                    dsd.IsHomogeneous    = false;
                    dsd.DestinationName  = destFile;
                    dsd.SheetSetName     = "PublisherSet";
                    dsd.PromptForDwfName = false;
                    PostProcessDSD(dsd, dsdFile);
                }

                var nbSheets = collection.Count;
                using (var progressDlg = new PlotProgressDialog(false, nbSheets, true))
                {
                    progressDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, title);
                    progressDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Отмена задания");
                    progressDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Отмена листа");
                    progressDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, title);
                    progressDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Печать листа");
                    progressDlg.UpperPlotProgressRange  = 100;
                    progressDlg.LowerPlotProgressRange  = 0;
                    progressDlg.UpperSheetProgressRange = 100;
                    progressDlg.LowerSheetProgressRange = 0;
                    progressDlg.IsVisible = true;
                    var publisher = Application.Publisher;
                    PlotConfigManager.SetCurrentConfig("clk-PDF.pc3");
                    publisher.PublishDsd(dsdFile, progressDlg);
                    progressDlg.Destroy();
                }

                NetLib.IO.Path.TryDeleteFile(dsdFile);

                // Добавить бланк
                if (Options.BlankOn)
                {
                    var tempPdf = NetLib.IO.Path.GetTempFile(".pdf");
                    try
                    {
                        var blank = IO.Path.GetLocalSettingsFile(@"Support\blank.pdf");
                        new PdfEditor().AddSheet(filePdfOutputName, blank, 1, Options.BlankPageNumber, tempPdf);
                        while (true)
                        {
                            try
                            {
                                File.Copy(tempPdf, filePdfOutputName, true);
                                Process.Start(filePdfOutputName);
                                break;
                            }
                            catch
                            {
                                var res = MessageBox.Show($"Закройте pdf файл - {filePdfOutputName}",
                                                          "Ошибка добавление бланка", MessageBoxButtons.OKCancel);
                                if (res != DialogResult.OK)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    finally
                    {
                        NetLib.IO.Path.TryDeleteFile(tempPdf);
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 11
0
        public static void PublishViews2MultiSheet()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;
            var ed  = doc.Editor;

            var viewsToPlot = new StringCollection();

            viewsToPlot.Add("Test1");
            viewsToPlot.Add("Test2");
            viewsToPlot.Add("Current");
            // Create page setup based on the views
            using (var Tx = db.TransactionManager.StartTransaction())
            {
                var layoutId = LayoutManager.Current.GetLayoutId
                                   (LayoutManager.Current.CurrentLayout);

                var layout
                    = Tx.GetObject(layoutId, OpenMode.ForWrite) as Layout;

                foreach (var viewName in viewsToPlot)
                {
                    var plotSettings
                        = new PlotSettings(layout.ModelType);
                    plotSettings.CopyFrom(layout);

                    var 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,
                        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();
            }

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

            Application.SetSystemVariable("BACKGROUNDPLOT", 0);

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

            using (var Tx = db.TransactionManager.StartTransaction())
            {
                var collection = new DsdEntryCollection();
                var activeLayoutId
                    = LayoutManager.Current.GetLayoutId
                          (LayoutManager.Current.CurrentLayout);

                foreach (var viewName in viewsToPlot)
                {
                    var layout = Tx.GetObject(
                        activeLayoutId,
                        OpenMode.ForRead
                        ) as Layout;

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

                // remove the ".dwg" extension
                dwgFileName = dwgFileName.Substring(0, dwgFileName.Length - 4);

                var dsdData = new DsdData();

                dsdData.SheetType   = SheetType.MultiDwf;
                dsdData.ProjectPath = dwgPath;
                dsdData.DestinationName
                    = dsdData.ProjectPath + dwgFileName + ".dwf";

                if (File.Exists(dsdData.DestinationName))
                {
                    File.Delete(dsdData.DestinationName);
                }

                dsdData.SetDsdEntryCollection(collection);

                var dsdFile
                    = dsdData.ProjectPath + dwgFileName + ".dsd";

                //Workaround to avoid promp for pdf file name
                //set PromptForDwfName=FALSE in dsdData using StreamReader/StreamWriter

                dsdData.WriteDsd(dsdFile);

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

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

                // Workaround to have the page setup names included in the DSD file
                // Replace Setup names based on the created page setups
                // May not be required if Nps is output to the DSD
                var occ        = 0;
                var index      = str.IndexOf("Setup=");
                var startIndex = 0;
                var dsdText    = new StringBuilder();
                while (index != -1)
                {
                    // 6 for length of "Setup="
                    var 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++;
                }

                // Write the DSD
                var sw
                    = new StreamWriter(dsdFile);
                sw.Write(dsdText.ToString());
                sw.Close();

                // Read the updated DSD file
                dsdData.ReadDsd(dsdFile);

                // Erase DSD as it is no longer needed
                File.Delete(dsdFile);

                var plotConfig
                    = PlotConfigManager.SetCurrentConfig("DWF6 ePlot.pc3");

                var publisher = Application.Publisher;

                // Publish it
                publisher.PublishExecute(dsdData, plotConfig);

                Tx.Commit();
            }

            //reset the background plot value
            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);
        }
Esempio n. 12
0
        public static void PublishLayouts(string path, string hole)
        {
            var completepath = Path.ChangeExtension(path, "pdf");

            var filename = Application.DocumentManager.MdiActiveDocument.Name;

            using (DsdEntryCollection dsdDwgFiles = new DsdEntryCollection())
            {
                // Define the first layout
                using (DsdEntry dsdDwgFile1 = new DsdEntry())
                {
                    // Set the file name and layout
                    dsdDwgFile1.DwgName = filename;
                    dsdDwgFile1.Layout  = "PGA-OUTPUT";
                    dsdDwgFile1.Title   = "PGA TOUR AUTOGENERATED SURFACE";

                    // Set the page setup override
                    dsdDwgFile1.Nps          = "";
                    dsdDwgFile1.NpsSourceDwg = "";

                    dsdDwgFiles.Add(dsdDwgFile1);
                }
                #region Define Second Layout

                //// Define the second layout
                //using (DsdEntry dsdDwgFile2 = new DsdEntry())
                //{
                //    // Set the file name and layout
                //    dsdDwgFile2.DwgName = "C:\\AutoCAD\\Samples\\Sheet Sets\\Architectural\\A-02.dwg";
                //    dsdDwgFile2.Layout = "ELEVATIONS";
                //    dsdDwgFile2.Title = "A-02 ELEVATIONS";

                //    // Set the page setup override
                //    dsdDwgFile2.Nps = "";
                //    dsdDwgFile2.NpsSourceDwg = "";

                //    dsdDwgFiles.Add(dsdDwgFile2);
                //}
                #endregion


                #region Define third layout
                //// Define the second layout
                using (DsdEntry dsdDwgFile2 = new DsdEntry())
                {
                    // Set the file name and layout
                    dsdDwgFile2.DwgName = filename;
                    dsdDwgFile2.Layout  = "ELEVATIONS";
                    dsdDwgFile2.Title   = "A-02 ELEVATIONS";


                    // Set the page setup override
                    dsdDwgFile2.Nps          = "";
                    dsdDwgFile2.NpsSourceDwg = @"C:\Users\m4800\AppData\Roaming\Autodesk\ApplicationPlugins\PGA-CivilTinSurf2016.bundle\Contents\Template\PGA_PRINT_TMPLT.dwg";
                    dsdDwgFiles.Add(dsdDwgFile2);
                }
                #endregion

                // Set the properties for the DSD file and then write it out
                using (DsdData dsdFileData = new DsdData())
                {
                    dsdFileData.PromptForDwfName = false;
                    // Set the target information for publishing
                    //dsdFileData.DestinationName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\PGA-Publish.pdf";
                    //dsdFileData.ProjectPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\";
                    dsdFileData.DestinationName = completepath;    //PGA-Publish.pdf;
                    dsdFileData.ProjectPath     = Path.GetDirectoryName(completepath);

                    dsdFileData.SheetType = SheetType.MultiPdf;

                    // Set the drawings that should be added to the publication
                    dsdFileData.SetDsdEntryCollection(dsdDwgFiles);

                    // Set the general publishing properties
                    //dsdFileData.LogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\myBatch.txt";
                    dsdFileData.LogFilePath = Path.ChangeExtension(path, "txt"); // "\\myBatch.txt";


                    // Create the DSD file
                    //dsdFileData.WriteDsd(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\batchdrawings2.dsd");
                    dsdFileData.WriteDsd(Path.ChangeExtension(path, "dsd")); //"\\batchdrawings2.dsd");
                    try
                    {
                        // Publish the specified drawing files in the DSD file, and
                        // honor the behavior of the BACKGROUNDPLOT system variable

                        using (DsdData dsdDataFile = new DsdData())
                        {
                            //dsdDataFile.ReadDsd(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\batchdrawings2.dsd");
                            dsdDataFile.ReadDsd(Path.ChangeExtension(path, "dsd")); // + "\\batchdrawings2.dsd");
                            // Get the DWG to PDF.pc3 and use it as a
                            // device override for all the layouts
                            PlotConfig acPlCfg = PlotConfigManager.SetCurrentConfig("DWG to PDF.PC3");

                            Application.Publisher.PublishExecute(dsdDataFile, acPlCfg);
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception es)
                    {
                        MessengerManager.MessengerManager.LogException(es);
                    }
                }
            }
        }
Esempio n. 13
0
        public static void SaveAsPDF(ResultBuffer rbArgs)
        {
            var editor = Acad.DocumentManager.MdiActiveDocument.Editor;

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


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

                                MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
                                plotter.Publish();
                                editor.WriteMessage(Environment.NewLine + dwgDB.Filename + " успешно экспортирован");
                                acTrans.Commit();
                            }
                        }
                    }
                    Acad.SetSystemVariable("BACKGROUNDPLOT", bgp);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {
                    editor.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
                }
            }
        }
Esempio n. 14
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);
            }