Export Layout

aruntr
Advocate
Advocate

Export Layout

aruntr
Advocate
Advocate

Sorry i saw may topics regarding this, but nothing works for me.

I am trying to saveas each layout to a separate dwg and delete the other layouts from exported dwg file. Partially this code  works. but for eg; if you have 3 layout in one dwg then it saveas  3 separate dwgs but other layouts are still there with layout name as layout1, layout2, layout3 etc. anyone help on this?

    // Process selected files
    foreach (string file in _selectedFiles)
    {
        using (Database db = new Database(false, true))
        {
            db.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, null);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

                try
                {
                    ExportAllLayouts(file);
                }
                catch (System.Exception ex)
                {
                    throw new System.Exception($"\nError exporting layouts: {ex.Message}", ex);
                }

                tr.Commit();
            }

            // Update progress
            progress += progressStep;
            progressBar1.Value = progress;
        }
    }

    progressBar1.Value = progressBar1.Maximum;
    Application.ShowAlertDialog("Layouts Exported Successfully");
}


public void ExportAllLayouts(string file)
{
    using (Database db = new Database(false, true))
    {
        db.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, null);
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            DBDictionary layoutDICT = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead);
            foreach (DBDictionaryEntry dictEntry in layoutDICT)
            {
                Layout layout = (Layout)tr.GetObject(dictEntry.Value, OpenMode.ForRead);
                if (!layout.ModelType)
                {
                    string layoutName = layout.LayoutName;
                    string dwgDestPathname = Regex.Replace(file, ".dwg", $"_{layoutName}.dwg");
                    MessageBox.Show(dwgDestPathname, "Destination Path Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    ExportSingleLayout(file, dwgDestPathname, layoutName);
                }
            }
            tr.Commit();
        }
    }
}

public void ExportSingleLayout(string dwgSourcePathname, string dwgDestPathname, string layoutNameToExport = null)
{
    using (Database db = new Database(false, true))
    {
        db.ReadDwgFile(dwgSourcePathname, FileOpenMode.OpenForReadAndAllShare, false, null);

        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            // Retrieve the layout dictionary
            DBDictionary layoutDICT = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForWrite);

            // If no layout name is provided, set the first non-model layout as the default
            if (string.IsNullOrEmpty(layoutNameToExport))
            {
                foreach (DBDictionaryEntry dictEntry in layoutDICT)
                {
                    Layout layout = (Layout)tr.GetObject(dictEntry.Value, OpenMode.ForRead);
                    if (!layout.ModelType) // Ensure it's not the Model space
                    {
                        MessageBox.Show(layoutNameToExport, "Layouts Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        layoutNameToExport = layout.LayoutName;
                        break;
                    }
                }
            }

            // If still no valid layout, throw an exception
            if (string.IsNullOrEmpty(layoutNameToExport))
            {
                throw new System.Exception("No valid layout found to export.");
            }
            tr.Commit();
        }

        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            DBDictionary layoutDict = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

            foreach (DBDictionaryEntry de in layoutDict)
            {
                string layoutName = de.Key;
                string Layouttokeep = Path.GetFileNameWithoutExtension(layoutNameToExport);

                MessageBox.Show(layoutName, "Layout Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                if (layoutName != "Model" && layoutName != Layouttokeep)
                {
                    ObjectId layoutId = (ObjectId)de.Value;

                    try
                    {
                        Layout layout = tr.GetObject(layoutId, OpenMode.ForWrite) as Layout;
                        LayoutManager lm = LayoutManager.Current;
                        if (layout != null)
                        {
                            lm.DeleteLayout(layoutName);
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception)
                    {

                    }
                }
            }

            tr.Commit(); // Commit the transaction.
        }

        // Save the modified file to a temporary location
        string tmpPathname = Path.GetTempFileName();
            MessageBox.Show(tmpPathname, "Temp Save", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            db.SaveAs(tmpPathname, DwgVersion.Current);

            // Ensure no file locks or issues when moving
            if (File.Exists(dwgDestPathname))
            {
                try
                {
                    File.Delete(dwgDestPathname);
                }
                catch (IOException ex)
                {
                    throw new System.Exception($"Failed to delete the old file: {dwgDestPathname}. Error: {ex.Message}");
                }
            }

            // Move the temporary file to the destination path
            File.Move(tmpPathname, dwgDestPathname);
            MessageBox.Show(dwgDestPathname, "Actual Save", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
           
        }
    }

 

0 Likes
Reply
226 Views
1 Reply
Reply (1)

ActivistInvestor
Advisor
Advisor

I've seen a number of attempts at doing this, and pretty much all of them worked by copying each layout to a new DWG file, and then xreferencing the source DWG file's model space into the drawing, to avoid duplicating it in each single-layout drawing. The result was multiple single-layout DWG files, each referencing the original source DWG's model space.

 

I can't think of a scenario where it should be possible to edit the model space contents of the single-layout drawings.

 

This is basically how they work:

 

  1. Read the original DWG file into a Database, and call CloseInput();
  2. Erase the entire contents of the drawing's Model space.
  3. Erase all but one layout in the Database.
  4. Save the Database to the destination filename.
  5. XRef attach the original drawing and insert that into model space with the default insertion parameters.
  6. Save the Database.

The above would be repeated for each Layout that is to be saved to its own DWG file.

0 Likes