Convert the DWG to PNG image using Plot API.

Convert the DWG to PNG image using Plot API.

aniket_pachore
Enthusiast Enthusiast
636 Views
5 Replies
Message 1 of 6

Convert the DWG to PNG image using Plot API.

aniket_pachore
Enthusiast
Enthusiast

I am using the AutoCAD Plot API to export a user-selected window area from model space to a PNG file. However, I'm encountering the following issue:

1. When I select a window area (as shown in Image1), I want that exact same area to be exported as a PNG.
But the output shows a different area (as seen in Output_Image).

I have tried several approaches to adjust the scale, such as using StdScaleType.ScaleToFit and SetCustomPrintScale, but none of them have worked for me.

Can anyone help me resolve this issue?

Attached Below code for your Reference

aniket_pachore_0-1745994327366.png

aniket_pachore_1-1745994364303.png

 

[CommandMethod("DWGTOIMG")]
public void ExportDWGToImage()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Editor ed = doc.Editor;
    Database db = doc.Database;

    // Prompt for output file
    PromptSaveFileOptions saveOpts = new PromptSaveFileOptions("\nSelect output PNG file location:");
    saveOpts.Filter = "PNG Files (*.png)|*.png";
    PromptFileNameResult saveResult = ed.GetFileNameForSave(saveOpts);
    if (saveResult.Status != PromptStatus.OK) return;
    string outputPath = saveResult.StringResult;

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        LayoutManager layoutMgr = LayoutManager.Current;
        ObjectId currentLayoutId = layoutMgr.GetLayoutId(layoutMgr.CurrentLayout);
        Layout layout = tr.GetObject(currentLayoutId, OpenMode.ForRead) as Layout;

        if (!layout.ModelType)
        {
            ed.WriteMessage("\nPlease switch to Model space (Model tab) first.");
            return;
        }

        PlotSettings plotSettings = new PlotSettings(layout.ModelType);
        plotSettings.CopyFrom(layout);

        PlotSettingsValidator psv = PlotSettingsValidator.Current;

        // Select window area
        PromptPointResult ppr1 = ed.GetPoint("\nSelect first corner of window: ");
        if (ppr1.Status != PromptStatus.OK) return;

        PromptCornerOptions pco = new PromptCornerOptions("\nSelect opposite corner: ", ppr1.Value);
        PromptPointResult ppr2 = ed.GetCorner(pco);
        if (ppr2.Status != PromptStatus.OK) return;

        Point2d lowerLeft = new Point2d(
        Math.Min(ppr1.Value.X, ppr2.Value.X),
        Math.Min(ppr1.Value.Y, ppr2.Value.Y)
        );
        Point2d upperRight = new Point2d(
        Math.Max(ppr1.Value.X, ppr2.Value.X),
        Math.Max(ppr1.Value.Y, ppr2.Value.Y)
        );
        //Extents2d windowArea = new Extents2d(ConvertMmToInches(lowerLeft), ConvertMmToInches(upperRight));
        Extents2d windowArea = new Extents2d(lowerLeft, upperRight);

        // Plot window area
        psv.SetPlotWindowArea(plotSettings, windowArea);
        psv.SetPlotType(plotSettings, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

        // Set plot configuration to PNG
        string deviceName = "PublishToWeb PNG.pc3";
        string mediaName = "Sun_Hi-Res_(1600.00_x_1280.00_Pixels)";
        psv.SetPlotConfigurationName(plotSettings, deviceName, null);
        //psv.RefreshLists(plotSettings);

        // Set paper size
        var mediaList = psv.GetCanonicalMediaNameList(plotSettings);
        if (mediaList.Contains(mediaName))
        {
            psv.SetCanonicalMediaName(plotSettings, mediaName);
        }
        else
        {
            ed.WriteMessage("\nMedia size not found. Using default.");
        }

        // Set standard scale to "Scale to Fit"
        psv.SetUseStandardScale(plotSettings, true);
        psv.SetStdScaleType(plotSettings, StdScaleType.ScaleToFit);
        //psv.SetUseStandardScale(plotSettings, false);
        //psv.SetCustomPrintScale(plotSettings, new CustomScale(1, 25.4));

        // Center the plot
        psv.SetPlotCentered(plotSettings, true);

        // Set rotation (optional, based on your layout)
        psv.SetPlotRotation(plotSettings, PlotRotation.Degrees000);

        psv.RefreshLists(plotSettings);

        // PlotInfo setup
        PlotInfo plotInfo = new PlotInfo();
        plotInfo.Layout = currentLayoutId;
        plotInfo.OverrideSettings = plotSettings;

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

        // Begin plotting
        if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
        {
            using (PlotEngine pe = PlotFactory.CreatePublishEngine())
            {
                using (PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true))
                {
                    ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Exporting DWG to PNG");
                    ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                    ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Progress");
                    ppd.LowerPlotProgressRange = 0;
                    ppd.UpperPlotProgressRange = 100;
                    ppd.PlotProgressPos = 0;

                    ppd.OnBeginPlot();
                    ppd.IsVisible = true;

                    pe.BeginPlot(ppd, null);

                    if (File.Exists(outputPath))
                        File.Delete(outputPath);

                    pe.BeginDocument(plotInfo, doc.Name, null, 1, true, outputPath);

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

                    ppd.OnEndPlot();
                    ed.WriteMessage("\nExport completed! PNG saved at: {0}", outputPath);
                }
            }
        }

        tr.Commit();
    }
}

 

0 Likes
Accepted solutions (1)
637 Views
5 Replies
Replies (5)
Message 2 of 6

pendean
Community Legend
Community Legend
Accepted solution

Why not use an image capture tool instead? Windows alone comes with at least one, most of us prefer the free and not so free dozens of others that have been around for decades @aniket_pachore 

 

0 Likes
Message 3 of 6

aniket_pachore
Enthusiast
Enthusiast

You're absolutely right. However, I also need to process the data after capturing a specific area. For example, if I capture the ground floor from a DWG file, I want to calculate the floor area of each room, as well as the area and count of doors and windows. That's why I'm planning to using the Plot API.
Thank you for suggesting the image capture tool; it’s a valuable option to consider.

0 Likes
Message 4 of 6

ActivistInvestor
Mentor
Mentor

You are going to calculate floor areas and count doors and windows off of a .PNG image?

0 Likes
Message 5 of 6

aniket_pachore
Enthusiast
Enthusiast

No, not from the PNG image
But the entities from the area of window selection.

0 Likes
Message 6 of 6

aniket_pachore
Enthusiast
Enthusiast

"I am unable to map the plot page and model space coordinates using the code below.
I would really appreciate it if anyone could test it."

[CommandMethod("DWGTOIMG")]
public void ExportDWGToImage()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Editor ed = doc.Editor;
    Database db = doc.Database;

    string outputPath = "D:\\Data\\Export.png";

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        LayoutManager layoutMgr = LayoutManager.Current;
        ObjectId currentLayoutId = layoutMgr.GetLayoutId(layoutMgr.CurrentLayout);
        Layout layout = tr.GetObject(currentLayoutId, OpenMode.ForRead) as Layout;

        if (!layout.ModelType)
        {
            ed.WriteMessage("\nPlease switch to Model space (Model tab) first.");
            return;
        }

        //PlotSettings plotSettings = new PlotSettings(layout.ModelType);
        //plotSettings.CopyFrom(layout);

        // Create new PlotSettings for model space
        PlotSettings plotSettings = new PlotSettings(true); // true = model space

        PlotSettingsValidator psv = PlotSettingsValidator.Current;

        // Select window area
        PromptPointResult ppr1 = ed.GetPoint("\nSelect first corner of window: ");
        if (ppr1.Status != PromptStatus.OK) return;

        PromptCornerOptions pco = new PromptCornerOptions("\nSelect opposite corner: ", ppr1.Value);
        PromptPointResult ppr2 = ed.GetCorner(pco);
        if (ppr2.Status != PromptStatus.OK) return;

        Point2d lowerLeft = new Point2d(
            Math.Min(ppr1.Value.X, ppr2.Value.X),
            Math.Min(ppr1.Value.Y, ppr2.Value.Y)
        );
        Point2d upperRight = new Point2d(
            Math.Max(ppr1.Value.X, ppr2.Value.X),
            Math.Max(ppr1.Value.Y, ppr2.Value.Y)
        );

        Extents2d windowArea = new Extents2d(lowerLeft, upperRight);

        // Set plot configuration to PNG + media size
        string deviceName = "PublishToWeb PNG.pc3";
        string mediaName = "Sun_Hi-Res_(1600.00_x_1280.00_Pixels)";
        psv.SetPlotConfigurationName(plotSettings, deviceName, null);
        psv.RefreshLists(plotSettings);

        var mediaList = psv.GetCanonicalMediaNameList(plotSettings);
        if (mediaList.Contains(mediaName))
        {
            psv.SetCanonicalMediaName(plotSettings, mediaName);
        }
        else
        {
            ed.WriteMessage("\nMedia size not found. Using default.");
        }

        // Set plot area and window
        psv.SetPlotWindowArea(plotSettings, windowArea);
        psv.SetPlotType(plotSettings, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

        double modelWidth = upperRight.X - lowerLeft.X;
        double modelHeight = upperRight.Y - lowerLeft.Y;

        double paperWidth = 1600.0; // in pixels
        double paperHeight = 1280.0;

        double scaleX = paperWidth / modelWidth;
        double scaleY = paperHeight / modelHeight;

        // Use the smaller scale to fit both dimensions
        double pixelsPerModelUnit = Math.Min(scaleX, scaleY);

        // Set custom scale as 1 paper unit = N model units
        psv.SetUseStandardScale(plotSettings, false);
        psv.SetCustomPrintScale(plotSettings, new CustomScale(1.0, 1.0 / pixelsPerModelUnit));
        psv.SetPlotCentered(plotSettings, true);

        // Set plot style
        psv.SetCurrentStyleSheet(plotSettings, "acad.ctb");

        // Orientation
        psv.SetPlotRotation(plotSettings, PlotRotation.Degrees000); // Landscape

        // Additional plot options
        plotSettings.PrintLineweights = true;
        plotSettings.PlotTransparency = true;
        plotSettings.PlotPlotStyles = true;
        plotSettings.ShadePlot = PlotSettingsShadePlotType.AsDisplayed;

        // PlotInfo setup
        PlotInfo plotInfo = new PlotInfo();
        plotInfo.Layout = currentLayoutId;
        plotInfo.OverrideSettings = plotSettings;

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

        // Begin plotting
        if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
        {
            using (PlotEngine pe = PlotFactory.CreatePublishEngine())
            {
                using (PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true))
                {
                    ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Exporting DWG to PNG");
                    ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                    ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Progress");
                    ppd.LowerPlotProgressRange = 0;
                    ppd.UpperPlotProgressRange = 100;
                    ppd.PlotProgressPos = 0;

                    ppd.OnBeginPlot();
                    ppd.IsVisible = true;

                    pe.BeginPlot(ppd, null);

                    if (File.Exists(outputPath))
                        File.Delete(outputPath);

                    pe.BeginDocument(plotInfo, doc.Name, null, 1, true, outputPath);

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

                    ppd.OnEndPlot();
                    ed.WriteMessage("\nExport completed! PNG saved at: {0}", outputPath);
                }
            }
        }
        tr.Commit();
    }
}

@pendean 
@ActivistInvestor 

0 Likes