Plot to PDF not working.

Plot to PDF not working.

luckyboy82292
Advocate Advocate
982 Views
6 Replies
Message 1 of 7

Plot to PDF not working.

luckyboy82292
Advocate
Advocate

Hi everyone!

I have developed an application which open a dialog window to select multiple drawing files and prompt user to specify the layer name, then iterate through all files one by one and select a rectangle by the user specified layer. And then make its vertices the plot area and then plot to pdf. But it's doing nothing. I don't understand why? Need help.

 

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.PlottingServices;
using Autodesk.AutoCAD.Runtime;
using System;
using System.IO;
using System.Windows.Forms;
using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;

namespace PlotMultiDrawingsToPdf
{
    public class Class1 : IExtensionApplication
    {
        #region
        public void Initialize()
        {
            
        }
        public void Terminate()
        {
            
        }
        #endregion
        [CommandMethod("OO")]
        public void ProcessFilesSelection()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed = doc.Editor;
            var dir = Path.GetDirectoryName(doc.Name);
            try
            {
                var openFileDialog = new OpenFileDialog()
                {
                    Multiselect = true,
                    InitialDirectory = dir,
                    Filter = "DWG Files (*.dwg) | *.dwg"
                };                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    var layerName = string.Empty;
                    while (string.IsNullOrEmpty(layerName))
                    {
                        var layResult = ed.GetString("\nEnter the layer name: ");
                        if (layResult.Status != PromptStatus.OK)
                        {
                            ed.WriteMessage("\nUser canceled input. Exiting...");
                            return;
                        }
                        layerName = layResult.StringResult.Trim();
                        if (string.IsNullOrEmpty(layerName))
                        {
                            ed.WriteMessage("\nEmpty layer name. Please enter a valid layer name.");
                        }
                    }
                    foreach (var file in openFileDialog.FileNames)
                    {
                        SearchObjectByLayer(file, layerName);
                    }
                }
                else
                {
                    ed.WriteMessage("\nNo files selected. Exiting...");
                    return;
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
            }
        }
        static void SearchObjectByLayer(string fileName, string layerName)
        {
            try
            {
                using (var db = new Database(false, true))
                {
                    var path = Path.GetFullPath(fileName);
                    
                    db.ReadDwgFile(fileName, FileShare.ReadWrite, true, "");
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                        foreach (ObjectId entId in btr)
                        {
                            var ent = tr.GetObject(entId, OpenMode.ForRead) as Entity;
                            if (ent != null && ent.Layer.Equals(layerName, StringComparison.OrdinalIgnoreCase) && ent is Polyline polyLine && polyLine.NumberOfVertices == 4)
                            {
                                var point1 = polyLine.GetPoint3dAt(0);
                                var point2 = polyLine.GetPoint3dAt(2);
                                ProcessPlotToPdf(fileName, point1, point2, Path.Combine(path + "\\PDF"));
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Console.WriteLine($"Error processing file: {fileName}\n{ex.Message}");
            }
        }
        static void ProcessPlotToPdf(string fileName,  Point3d point1, Point3d point2, string path)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            try
            {
                using (var db = new Database(false, true))
                {
                    db.ReadDwgFile(fileName, FileShare.ReadWrite, true, "");
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                        var layout = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                        PlotSettings plotSettings = new PlotSettings(layout.ModelType);
                        plotSettings.CopyFrom(layout);
                        var plotSettingsValidator = PlotSettingsValidator.Current;
                        Extents2d plotWindowExtents = new Extents2d(new Point2d(point1.X, point1.Y), new Point2d(point2.X, point2.Y));
                        plotSettings.ScaleLineweights = true;
                        plotSettingsValidator.SetPlotWindowArea(plotSettings, plotWindowExtents);
                        plotSettingsValidator.SetPlotType(plotSettings, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                        plotSettingsValidator.SetUseStandardScale(plotSettings, true);
                        plotSettingsValidator.SetStdScaleType(plotSettings, StdScaleType.ScaleToFit);
                        plotSettingsValidator.SetPlotRotation(plotSettings, PlotRotation.Degrees180);
                        plotSettingsValidator.SetPlotCentered(plotSettings, false);
                        plotSettingsValidator.SetPlotConfigurationName(plotSettings, "DWG To PDF.pc3", "ISO_full_bleed_A4_(210.00_x_297.00_MM)");
                        PlotInfo plotInfo = new PlotInfo
                        {
                            Layout = btr.LayoutId,
                            OverrideSettings = plotSettings
                        };
                        PlotInfoValidator piv = new PlotInfoValidator
                        {
                            MediaMatchingPolicy = MatchingPolicy.MatchEnabled
                        };
                        piv.Validate(plotInfo);

                        tr.Commit();

                        using (PlotEngine plotEngine = PlotFactory.CreatePublishEngine())
                        {
                            plotEngine.BeginPlot(null, null);
                            plotEngine.BeginDocument(plotInfo, doc.Name, null, 1, true, path);
                            PlotPageInfo pageInfo = new PlotPageInfo();
                            try
                            {
                                plotEngine.BeginPage(pageInfo, plotInfo, true, null);

                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                            plotEngine.BeginGenerateGraphics(null);
                            plotEngine.EndGenerateGraphics(null);
                            plotEngine.EndPage(null);
                            plotEngine.EndDocument(null);
                            plotEngine.EndPlot(null);
                        }
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Console.WriteLine($"Error plotting file: {fileName}\n{ex.Message}");
            }
        }
    }
}
0 Likes
Accepted solutions (1)
983 Views
6 Replies
Replies (6)
Message 2 of 7

_gile
Consultant
Consultant

Hi,

You should define a method which takes a Database as argument (and possibly a layer Name) to be able to test and debug this method in the current drawing by calling it from a CommandMethod.

And when you're satisfied with the result, you can pass this method to a 'BatchProcess' one (see this example).



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 3 of 7

luckyboy82292
Advocate
Advocate
I have debugged the code. And got this: "eRepeatedDwgReadError plotting file"
0 Likes
Message 4 of 7

luckyboy82292
Advocate
Advocate

I have changed the code look like this, but the error still exist. It says "eLayoutNotCurrent". But if we look at code there is no issue. It should work without error but not. Could you please take a look and spot the error?

Here is code:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.PlottingServices;
using Autodesk.AutoCAD.Runtime;
using System;
using System.IO;
using System.Windows.Forms;
using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;

namespace PlotMultiDrawingsToPdf
{
    public class Class1 : IExtensionApplication
    {
        #region
        public void Initialize()
        {

        }
        public void Terminate()
        {

        }
        #endregion
        [CommandMethod("OO")]
        public void ProcessFilesSelection()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed = doc.Editor;
            var dir = Path.GetDirectoryName(doc.Name);
            var openFileDialog = new OpenFileDialog()
            {
                Multiselect = true,
                InitialDirectory = dir,
                Filter = "DWG Files (*.dwg) | *.dwg"
            }; if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var layerName = string.Empty;
                while (string.IsNullOrEmpty(layerName))
                {
                    var layResult = ed.GetString("\nEnter the layer name: ");
                    if (layResult.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\nUser canceled input. Exiting...");
                        return;
                    }
                    layerName = layResult.StringResult.Trim();
                    if (string.IsNullOrEmpty(layerName))
                    {
                        ed.WriteMessage("\nEmpty layer name. Please enter a valid layer name.");
                    }
                }
                foreach (var file in openFileDialog.FileNames)
                {
                    SearchObjectByLayer(file, layerName);
                }
            }
            else
            {
                ed.WriteMessage("\nNo files selected. Exiting...");
                return;
            }
        }
        static void SearchObjectByLayer(string fileName, string layerName)
        {
            var ed = Application.DocumentManager.MdiActiveDocument.Editor;

            var path = Path.GetDirectoryName(fileName);
            try
            {
                using (var db = new Database(false, true))
                {
                    db.ReadDwgFile(fileName, FileShare.ReadWrite, false, "");
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                        foreach (ObjectId entId in btr)
                        {
                            var ent = tr.GetObject(entId, OpenMode.ForRead) as Entity;
                            if (ent != null && ent.Layer.Equals(layerName, StringComparison.OrdinalIgnoreCase) && ent is Polyline polyLine && polyLine.NumberOfVertices == 4)
                            {
                                var point1 = polyLine.GetPoint3dAt(0);
                                var point2 = polyLine.GetPoint3dAt(2);

                                ProcessPlotToPdf(tr, btr, point1, point2, Path.Combine(path + "\\PDF"));
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage($"\nError1: {ex.Message}");
            }
        }
        static void ProcessPlotToPdf(Transaction tr, BlockTableRecord btr, Point3d point1, Point3d point2, string path)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed = doc.Editor;
            try
            {
                var layout = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);
                PlotInfo plotInfo = new PlotInfo()
                {
                    Layout = btr.LayoutId
                };
                plotInfo.Layout = btr.LayoutId;
                var plotSettings = new PlotSettings(layout.ModelType);
                plotSettings.CopyFrom(layout);
                var plotSettingsValidator = PlotSettingsValidator.Current;
                var plotWindowExtents = new Extents2d(new Point2d(point1.X, point1.Y), new Point2d(point2.X, point2.Y));
                plotSettings.ScaleLineweights = true;
                plotSettingsValidator.SetPlotWindowArea(plotSettings, plotWindowExtents);
                plotSettingsValidator.SetPlotType(plotSettings, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                plotSettingsValidator.SetUseStandardScale(plotSettings, true);
                plotSettingsValidator.SetStdScaleType(plotSettings, StdScaleType.ScaleToFit);
                plotSettingsValidator.SetPlotRotation(plotSettings, PlotRotation.Degrees000);
                plotSettingsValidator.SetPlotCentered(plotSettings, false);
                plotSettingsValidator.SetPlotConfigurationName(plotSettings, "DWG To PDF.pc3", "ISO_full_bleed_A4_(210.00_x_297.00_MM)");
                plotInfo.OverrideSettings = plotSettings;
                var piv = new PlotInfoValidator
                {
                    MediaMatchingPolicy = MatchingPolicy.MatchEnabled
                };
                piv.Validate(plotInfo);

                PlotEngine pe = PlotFactory.CreatePublishEngine();
                using (pe)
                {
                    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(plotInfo, doc.Name, null, 1, true, path);
                        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);
                        ppd.PlotProgressPos = 100;
                        ppd.OnEndPlot();
                        pe.EndPlot(null);
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage($"\nError3: {ex.Message}");
            }
        }
    }
}

 

0 Likes
Message 5 of 7

luckyboy82292
Advocate
Advocate

Please help me with this. Thank you!

0 Likes
Message 6 of 7

_gile
Consultant
Consultant
Accepted solution

Hi,

You got "eLayoutNotCurrent" because the 'side database' is not the working database.

You have to temporarily set this 'side database' as working database while plotting and restore the previous working database before disposing it. To do it, you can use the WorkingDatabase class from "ActivistInvestor" (AKA Tony Tanzillo).

That said, I think using the 'side database' way to do batch plotting is not a so good idea. You could define a Command to plot the current drawing and use the accoreconsole for the batch processing.



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes
Message 7 of 7

luckyboy82292
Advocate
Advocate
Thank you Sir! You saved my time. It's working fine.
0 Likes