spotfiresoftware / spotfire-mods

Spotfire® Mods
https://spotfiresoftware.github.io/spotfire-mods/
Other
56 stars 41 forks source link

How to export a mod visualization to image (png) with IronPython #58

Closed mwdpb closed 2 years ago

mwdpb commented 2 years ago

Hi, I have a custom mod visualization that I'd like to export to png file with IronPython script. The script below works for a native Spotfire vis, but it failed on a mod vis. I then tried Spotfire native export button (File->Export->Visualization to image...) and it works just fine. So I believe it is achievable, can anyone help me on what API function I should use to accomplish this goal? Thank you!

from System.Drawing import Bitmap, Graphics, Rectangle, Point
from System.Drawing.Imaging import ImageFormat

for v in Document.ActivePageReference.Visuals:
    w, h = 100, 100
    bm = Bitmap(w, h)
    g = Graphics.FromImage(bm)
    g.TextRenderingHint = g.TextRenderingHint.AntiAlias
    _ = v.Render(g, Rectangle(Point(0, 0), bm.Size))
    fname = "G:\\test.jpg"
    bm.Save(fname, ImageFormat.Png)
objerke commented 2 years ago

Hi @mwdpb, You should use the newer Visual.RenderAsync method to render mods. The Visual.Render method is classified as obsolete.

The following code snippet is taken from this example and it works for mods.

from Spotfire.Dxp.Application.Visuals import *
from System.Drawing import Size
from System.Threading import CancellationToken 
from Spotfire.Dxp.Application.Visuals import RenderResultSettings

viz = Document.ActivePageReference.ActiveVisualReference
s=Size(1000,500)
rrs=RenderResultSettings(s)
vrs=VisualRenderSettings()
ct=CancellationToken()

renderResult=viz.RenderAsync(rrs,vrs,ct)
img=renderResult.Result.AsImage()
img.Save("C://temp//viz.png")

For more information about the Export APIs you can read this article.

mwdpb commented 2 years ago

Hi @objerke, thanks for the quick reply. I tried your code and result in the following error, any idea why?

image

objerke commented 2 years ago

Yes, you are not allowed to run the script in a transaction. There is a checkbox in the dialog screenshot that should not be checked. It is also mentioned in the linked example.

mwdpb commented 2 years ago

Got it, thank you very much! My previous scripting experience doesn't need to deal with threading, so I overlooked that note. Sorry about that!