How can I align a new object to the camera view with Python? I am trying to work out a script that adds a plane aligned to the camera view, but I cannot figure out how to do anything past it being aligned to the current view. This works fine mostly, as long as I am in the camera view, but it would be much more convenient to not have to be in camera view.

This is what I have so far:

import bpy

# Add a plane and align it to view
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        for region in area.regions:
            if region.type == 'WINDOW':
                ctx = bpy.context.copy()
                ctx['area'] = area
                ctx['region'] = region
                bpy.ops.mesh.primitive_plane_add(ctx, view_align=True)
                bpy.ops.object.editmode_toggle() # Avoid a missing face

# Add diffuse shader to object
activeObject = bpy.context.active_object
mat = bpy.data.materials.new(name="grey card")
activeObject.data.materials.append(mat)
bpy.context.object.active_material.diffuse_color = (.18, .18, .18)


I have seen this question, and the accepted answer says to assign the camera object's rotation_euler to the object to be aligned with C.object.rotation_euler = C.scene.camera.rotation_euler, but I am not sure what to do with this advice (as it may be evident, Python is not a strength, but I'm trying to learn).

What do I need to change in this script in order for it to work as I am wanting it to?
Since you want to align the object with the current view (and not the camera), you need to extract that view through the view 3D's region_3d (rv3d in the example below), then assign its rotation to the object you want to align the view with:

import bpy
def view3d_find( return_area = False ):
    # returns first 3d view, normally we get from context
    for area in bpy.context.window.screen.areas:
        if area.type == 'VIEW_3D':
            v3d = area.spaces[0]
            rv3d = v3d.region_3d
            for region in area.regions:
                if region.type == 'WINDOW':
                    if return_area: return region, rv3d, v3d, area
                    return region, rv3d, v3d
    return None, None

r3d, rv3d, v3d = view3d_find()

# Add new plane which will become the context object
bpy.ops.mesh.primitive_plane_add()

bpy.context.object.rotation_euler = rv3d.view_rotation.to_euler()