Sketch Text API Sample

Description

Demonstrates creating sketch text by creating both mult-line text and text along a curve.

Code Samples

import adsk.core, adsk.fusion, traceback

def run(context):
    ui = None
    try: 
        app = adsk.core.Application.get()
        ui = app.userInterface

        # Create a new document and get the Design.
        doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        design: adsk.fusion.Design = app.activeProduct

        # Get the root component of the active design.
        rootComp = design.rootComponent

        # Create a new sketch on the XY construction plane.
        sk = rootComp.sketches.add(rootComp.xYConstructionPlane)

        # Get the SketchTexts collection object.
        texts = sk.sketchTexts

        # Add multi-line text.
        height = adsk.core.ValueInput.createByReal(0.5)
        input = texts.createInput3('\'This is a long line that is broken automatically.\n\nAnd this is a defined line break.\'', height)
        input.setAsMultiLine(adsk.core.Point3D.create(0, 0, 0),
                             adsk.core.Point3D.create(10, 5, 0),
                             adsk.core.HorizontalAlignments.LeftHorizontalAlignment,
                             adsk.core.VerticalAlignments.TopVerticalAlignment, 0)
        texts.add(input)

        # Draw an arc to use to create text along a curve.
        arc = sk.sketchCurves.sketchArcs.addByThreePoints(adsk.core.Point3D.create(-10, 0, 0),
                                                          adsk.core.Point3D.create(-5, 3, 0),
                                                          adsk.core.Point3D.create(0, 0, 0))

        # Create text along the arc.
        input = texts.createInput3('\'Text Along a Curve\'', adsk.core.ValueInput.createByString('0.25 in'))
        input.setAsAlongPath(arc, False, adsk.core.HorizontalAlignments.CenterHorizontalAlignment, 0)
        input.isHorizontalFlip = True
        input.isVerticalFlip = True
        input.fontName = 'Artifakt Element'
        texts.add(input)        
        
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#include <Core/Application/Application.h>
#include <Core/Application/Document.h>
#include <Core/Application/Documents.h>
#include <Core/Geometry/Point3D.h>
#include <Core/UserInterface/UserInterface.h>
#include <Fusion/Components/Component.h>
#include <Fusion/Construction/ConstructionPlane.h>
#include <Fusion/Fusion/Design.h>
#include <Fusion/Sketch/Sketches.h>
#include <Fusion/Sketch/Sketch.h>
#include <Fusion/Sketch/SketchCurves.h>
#include <Fusion/Sketch/SketchArcs.h>
#include <Fusion/Sketch/SketchArc.h>
#include <Fusion/Sketch/SketchTexts.h>
#include <Fusion/Sketch/SketchTextInput.h>
#include <Fusion/Sketch/SketchText.h>

using namespace adsk::core;
using namespace adsk::fusion;

Ptr<UserInterface> ui;

extern "C" XI_EXPORT bool run(const char* context)
{
    Ptr<Application> app = Application::get();
    if (!app)
        return false;

    ui = app->userInterface();
    if (!ui)
        return false;

    // Create a document and get the Design.
    Ptr<Document> doc = app->documents()->add(DocumentTypes::FusionDesignDocumentType);
    if (!doc)
        return false;

    Ptr<Design> design = app->activeProduct();
    if (!design)
        return false;

    // Get the root component of the active design
    Ptr<Component> rootComp = design->rootComponent();
    if (!rootComp)
        return false;

    // Create a new sketch on the XY construction plane.
    Ptr<Sketch> sk = rootComp->sketches()->add(rootComp->xYConstructionPlane());
    if (!sk)
        return false;

    // Get the SketchTexts collection object.
    Ptr<SketchTexts> texts = sk->sketchTexts();
    if (!texts)
        return false;

    // Add multi-line text.
    Ptr<SketchTextInput> input = texts->createInput2(
        "This is a long line that is broken automatically.\n\nAnd this is a defined line break.", 0.5);
    if (!input)
        return false;

    bool ret = input->setAsMultiLine(
        adsk::core::Point3D::create(0, 0, 0),
        adsk::core::Point3D::create(10, 5, 0),
        adsk::core::HorizontalAlignments::LeftHorizontalAlignment,
        adsk::core::VerticalAlignments::TopVerticalAlignment,
        0);
    if (!ret)
        return false;

    Ptr<SketchText> text = texts->add(input);
    if (!text)
        return false;

    // Draw an arc to use to create text along a curve.
    Ptr<SketchArc> arc = sk->sketchCurves()->sketchArcs()->addByThreePoints(
        adsk::core::Point3D::create(-10, 0, 0),
        adsk::core::Point3D::create(-5, 3, 0),
        adsk::core::Point3D::create(0, 0, 0));
    if (!arc)
        return false;

    // Create text along the arc.
    input = texts->createInput2("Text Along a Curve", 0.75);
    if (!input)
        return false;

    ret = input->setAsAlongPath(arc, false, adsk::core::HorizontalAlignments::CenterHorizontalAlignment, 0);
    if (!ret)
        return false;

    ret = input->isHorizontalFlip(true);
    if (!ret)
        return false;

    ret = input->isVerticalFlip(true);
    if (!ret)
        return false;

    ret = input->fontName("Comic Sans MS");
    if (!ret)
        return false;

    text = texts->add(input);
    if (!text)
        return false;

    return true;
}
/**
 * Sketch Text API Sample
 * Demonstrates creating sketch text by creating both mult-line text and text along a curve.
 */

import { adsk } from '@adsk/fusion';

//Params
// {
//     "useCurrentDocument": false,
//     "saveAsNewDocument": false,
//     "message": "",
//     "hubId": "wip1fqaautodesk4298",
//     "fileURN": "urn:adsk.wipqa:dm.lineage:WlSCDh7RQN6zD2btrrO4SA"
// }

function run() {
  
// Read the parameters passed with the script
  const scriptParameters = JSON.parse(adsk.parameters);
  if (!scriptParameters) throw Error("Invalid parameters provided.");

  // Get the Fusion API's application object
  const app = adsk.core.Application.get();
  if (!app) throw Error("No adsk.core.Application.");

  // const doc: adsk.core.Document = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType);
  // Create a new empty document
  const doc = getDocument(
    app,
    scriptParameters.useCurrentDocument,
    scriptParameters.hubId,
    scriptParameters.fileURN,
  );
  if (!doc) throw Error("Invalid document.");

 // Ensure we are in the Design environment.
  const design = app.activeProduct as adsk.fusion.Design;

  //Get the root component of the active design.
  const rootComp = design.rootComponent

  // Create a new sketch on the XY construction plane.
  const sk = rootComp.sketches.add(rootComp.xYConstructionPlane)

  // Get the SketchTexts collection object.
  const texts = sk.sketchTexts
  // Add multi-line text.
  const input = texts.createInput2('This is a long line that is broken automatically.\n\nAnd this is a defined line break.', 0.5)
  input.setAsMultiLine(adsk.core.Point3D.create(0, 0, 0),
                       adsk.core.Point3D.create(10, 5, 0),
                       adsk.core.HorizontalAlignments.LeftHorizontalAlignment,
                       adsk.core.VerticalAlignments.TopVerticalAlignment, 0)
  texts.add(input)
  // Draw an arc to use to create text along a curve.
  const arc = sk.sketchCurves.sketchArcs.addByThreePoints(adsk.core.Point3D.create(-10, 0, 0),
                                                    adsk.core.Point3D.create(-5, 3, 0),
                                                    adsk.core.Point3D.create(0, 0, 0))
  // Create text along the arc.
  const inputAlongTheArc = texts.createInput2('Text Along a Curve', 0.75)
  inputAlongTheArc.setAsAlongPath(arc, false, adsk.core.HorizontalAlignments.CenterHorizontalAlignment, 0)
  inputAlongTheArc.isHorizontalFlip = true
  inputAlongTheArc.isVerticalFlip = true
  inputAlongTheArc.fontName = 'Artifakt Element'
  texts.add(inputAlongTheArc)        
  
  saveDocument(
      doc,
      scriptParameters.saveAsNewDocument,
      scriptParameters.message,
      doc.dataFile.parentFolder,
    );

    while (app.hasActiveJobs) {
    wait(2000);
  }
}
function wait(ms: number) {
  const start = new Date().getTime();
  while (new Date().getTime() - start < ms) adsk.doEvents();
}

function getDocument(
  app: adsk.core.Application,
  useCurrentDocument: boolean,
  hubId: string,
  fileURN: string,
): adsk.core.Document {
  if (useCurrentDocument === true) {
    adsk.log(`Using currently open document: ${app.activeDocument.name}.`);
    return app.activeDocument;
  }

  if (hubId) {
    // Possible hubId formats: base64 encoded string, or business:<id>,
    // or personal:<id> (deprecated)
    const hub =
      app.data.dataHubs.itemById(hubId) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`business:${hubId}`, true)}`) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`personal:${hubId}`, true)}`);
    if (!hub) throw Error(`Hub with id ${hubId} not found.`);
    adsk.log(`Setting hub: ${hub.name}.`);
    app.data.activeHub = hub;
  }

  const file = app.data.findFileById(fileURN);
  if (!file) throw Error(`File not found ${fileURN}.`);
  adsk.log(`Opening ${file.name}`);
  const document = app.documents.open(file, true);
  if (!document) throw Error(`Cannot open file ${file.name}.`);
  return document;
}

function saveDocument(
  doc: adsk.core.Document,
  saveAsNewDocument: boolean,
  message: string,
  destinationFolder: adsk.core.DataFolder,
): boolean {
  if (saveAsNewDocument) {
    adsk.log("Saving as new document.");
    try {
      destinationFolder.parentProject;
    } catch (e) {
      adsk.log(
        "Destination folder is not in a project, setting folder to Fusion Automation Service project.",
      );
      destinationFolder = defaultFolder(
        doc.parent,
        "Fusion Automation Service",
      );
    }
    if (
      doc.saveAs(doc.name + " Additive Ready", destinationFolder, message, "")
    ) {
      adsk.log("Document saved successfully.");
      return true;
    } else {
      adsk.log("Document failed to save.");
      return false;
    }
  }

  if (!doc.isModified) {
    adsk.log("Document not modified, not saving.");
    return true;
  }

  adsk.log(`Saving with message: "${message}".`);
  if (doc.save(message)) {
    adsk.log("Document saved successfully.");
    return true;
  } else {
    adsk.log("Document failed to save.");
    return false;
  }
}

function defaultFolder(app: adsk.core.Application, defaultProjectName: string) {
  const projects = app.data.activeHub.dataProjects;
  if (!projects) throw Error("Unable to get active hub's projects.");
  for (let i = 0; i < projects.count; ++i) {
    const project = projects.item(i)!;
    if (project.name === defaultProjectName) {
      return project.rootFolder;
    }
  }
  adsk.log(`Creating new project: ${defaultProjectName}`);
  const project = projects.add(defaultProjectName);
  if (!project) throw Error("Unable to create new project.");
  return project.rootFolder;
}

run();