Insert and XREF

I want to create a script for inserting an AutoCAD XREF into an empty drawing and then selecting all its layers and changing them to color 251. My question though, is there a way to insert an XREF with Dynamo? All I see is the option to insert a block.


Hi @MSchille-1994,

There isn’t a dedicated node for this yet, so I put together this Python script for you to try. It doesn’t have any error checking, so it’s more of a proof of concept - use at your own risk.

IN[0] = the path to the DWG (as a string)
IN[1] = the name for the XREF (I just used the file name in this example)
IN[2] = a boolean toggle to set the XREF as Overlay or Attach (true is Overlay, false is Attach)

The output is the name of the XREF, which you can then feed into Document.BlockByName to create the block wrapper and then get the objects and their layers. At the end of it all, Layer.SetColor will be your friend.

FYI @Paolo_Emilio_Serra1 maybe something to add to the wish list.

import clr

# Add Assemblies for AutoCAD

# Import references from AutoCAD
from Autodesk.AutoCAD.ApplicationServices import *
from Autodesk.AutoCAD.DatabaseServices import *
from Autodesk.AutoCAD.Geometry import *

adoc = Application.DocumentManager.MdiActiveDocument
editor = adoc.Editor

def add_xref(path,blockName,switch):
	global adoc
	with adoc.LockDocument():
		with adoc.Database as db:
			with db.TransactionManager.StartTransaction() as t:
				# Determine whether to overlay or attach
				if switch==True:
					oid = db.OverlayXref(path, blockName)
					oid = db.AttachXref(path, blockName)
				if not oid.IsNull:
					insPt = Point3d(0, 0, 0)					
					# Create block reference
					blkRef = BlockReference(insPt,oid)
					# Add block table record
					bt = t.GetObject(db.BlockTableId, OpenMode.ForWrite)
					btr = t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite)
					t.AddNewlyCreatedDBObject(blkRef, True)		
	return blkRef.Name
OUT = add_xref(IN[0],IN[1],IN[2])

Hi that is a nice Python script!

Is there a way to make it work with multiple Xref? now when i’m feeding a list of path and name it return a error.

Any help will be geat!


You’d need to change the path and blockName inputs to be lists and then add a loop to iterate through each item in the list.

ok thanks, unfortunately im not very good (read no expentience at all) in Python :frowning: