Placing text onto pageview (layout) from Python

I am having a hard time navigating the nuances between viewports and pageviews. It seems that I cannot genereate text onto a layout unless it is the active view port. Is that the case ? I have been chipping away at the problem but fall just short of generating text onto a layout without it being the active view port.

Here I have placed four points on a layout. Three are to establish a plane and the fourth is the planes new origin. Once the plane is created and its origin is updated I go along to make a TextEntity object and create an object attributes object and populate it whit what I think is important. This works fine, but again it only works when I have the first layout open on my screen as the active viewport or set it as the active view port. Is there a way to have it populate text while not switching to the page view / layout view.

Thanks !

import rhinoscriptsyntax as rs
import scriptcontext as sc
import math

import System
import System.Collections.Generic
import Rhino as R

doc = sc.doc

objs = sc.doc.Objects

views = sc.doc.Views.GetPageViews()

for vi in views:
    if vi.PageName == 'Page 1':
        sc.doc.Views.ActiveView = vi

for ob in objs:
    if type(ob) == R.DocObjects.PointObject:
        if ob.Name == "t_len_a":
            text_origin_pt = rs.coerce3dpoint(ob.Id)
            v_id = ob.Attributes.ViewportId

        if ob.Name == "pp_o":
            base_p_o = rs.coerce3dpoint(ob.Id)
        if ob.Name == "pp_x":
            base_p_x = rs.coerce3dpoint(ob.Id)
        if ob.Name == "pp_y":
            base_p_y = rs.coerce3dpoint(ob.Id)

ds = sc.doc.DimStyles.Current

plane = R.Geometry.Plane(base_p_o,base_p_x,base_p_y)

plane.Origin = text_origin_pt

te = R.Geometry.TextEntity.Create("Hello", plane, ds, False, 0, 0)
te.TextHeight = 0.25

targh = R.DocObjects.ObjectAttributes()
targh.ViewportId = v_id
targh.SetObjectFrame = plane

t_id = objs.AddText(te,targh)


Hi @cncduck, below seems to work even if the page is not active:

import Rhino
import scriptcontext
import rhinoscriptsyntax as rs
def DoSomething():
    views = scriptcontext.doc.Views.GetPageViews()
    if not views: return
    page_name = "Page 1"
    page_view = next( (v for v in views if v.PageName == page_name), None)
    if not page_view: return
    plane = Rhino.Geometry.Plane.WorldXY
    plane.Origin = Rhino.Geometry.Point3d(10,20,0)
    te = Rhino.Geometry.TextEntity()
    te.Plane = plane
    te.Text = "Hello World"
    te.TextHeight = 10.0
    te.SetFacename(True, "Arial")
    attr = Rhino.DocObjects.ObjectAttributes()
    attr.Space = Rhino.DocObjects.ActiveSpace.PageSpace
    attr.ViewportId = page_view.ActiveViewportID
    scriptcontext.doc.Objects.AddText(te, attr)


Note that no detail should be activated on the page named eg. “Page 1”, otherwise the text will be added to that detail. If you want to add to the page in any case you can include this: