Process the macro in controller

Enonic version: 7.0.2
OS: Linux Mint

Is it possible to get the processed macro (inside HTMLArea field) in the controller?
I trying this two ways, but not works for me:

// Attempt 1 (using portal lib)
htmlWithMacro = portalLib.processHtml({
  value: htmlWithMacro,
  type: 'absolute'

// Attempt 2 (using thymeleaf)
model = {
  text: portalLib.processHtml({
    value: htmlWithMacro,
    type: 'absolute'
view = resolve('view.html')
htmlWithMacro = thymeleaf.render(view, model)

// view.html
<div data-th-utext="${text}"></div>

But these two attempts return this result:

<!--#MACRO _name=\"macroname\" text=\"mytext\" _document=\"__macroDocument1\" _body=\"\"-->

Macro processing happens after all components (i.e. parts, layouts, page template…) of a page have run and their results been spliced together into a document (typically HTML) that contains the macro comments that you end up with in your example. This means that by default it will not work to try to invoke your macro controller from for instance a part controller.

There are probably a few possible workarounds, but you’ll need to get creative. The only ones I can come up with at the moment require that you parse the macro and extract the parameters using your own code. Once that is done, you can for instance move the macro logic from the macro controller into a service that the macro passes the parameters to. In that way, you can simply pass the parameters you’ve parsed into that service, and it will give you the same result as if the macro was inserted normally during the page rendering process.

It would make things much simpler if there was a way to use the existing code inside Enonic XP that parses the macro for you, but I don’t know where that code lies. Perhaps in a Javascript library, or in some Java code that is exposed and can be made available in your controller with the newBean() method?

You could try using MacroService Java API via bean, as @bhj suggested