Using SVG in Xojo Web

Using SVG in Xojo Web

Loading pictures separately and storing them in properties is essential for the web toolbar. Why? Well, usually you will show the web toolbar on all (at least many) web pages, and it will (almost) always be the same for all users (means for all sessions of a running Xojo Web 2 Application).

Consequently “caching” these files is the way to go. Caching means in this case that you are basically loading the pictures only once per running app, and then they stay in a property (so in your server’s memory).

How to do this with SVG files?

Why to use SVG-Files at all? They scale better and easier and you will get a crispier result. Look at the following articles to get a better understanding of what I mean:

SVG is often the best and easiest way to get some cool and crisp outcomes.

1. Using a property

The “easiest” way would be to use a property defined as a string. Open your SVG file (which is an XML file) and copy & paste the content into the default value of your string variable. That’s the quick and dirty way.

But there are a few caveats with this:

  • You will need to put this string back into a file, in case you ever want to change your picture again.

  • Or you need to hold a copy of the original file.

  • Having fun with “Search & Replace” in the Xojo IDE. You either will get too many results or (more dangerous!) you might replace bits in this string by mistake (believe me, it is just too easy to make this happen).

  • If you have many SVG pictures this will bloat your code and slow down your searches (unless you exclude the location where you are storing these SVG data).

  • It looks ugly.

  • It’s ugly.

As we learned above that it makes anyway sense to keep at least one physical copy of your picture file, let’s read our SVG-file with Xojo. Let’s assume we have a file called “pvmag_logo.svg”, stored in the subfolder “img” in the resources-folder of our final app, the following code will read the content of this SVG-file into the web picture:

// Only read it once per running App   
If mPVMAGLogo Is Nil Then Var logoSVGFile As FolderItem = SpecialFolder.Resources.Child("img").Child("pvmag_logo.svg")   
Var svgData as string
// Ensure to copy your svg-file into the right path, let's check if this worked   
If logoSVGFile <> Nil And logoSVGFile.Exists Then Var t As TextInputStream
Try   
// As SVG consists of XML-based instructions, we can read it like text t = TextInputStream.Open( logoSVGFile )   
t.Encoding = Encodings.UTF8 svgData = t.ReadAll   
Catch e As IOException   
MessageBox("Error accessing the SVG")   
End Try
t.Close   
end if mPVMAGLogo = new WebPicture   
mPVMAGLogo.MIMEType = "image/svg+xml"
// important to make the picture available to all sessions of the running app   
mPVMAGLogo.Session = Nil   
mPVMAGLogo.Data = svgData
End If Return mPVMAGLogo

Did you find this article valuable?

Support jeannot-muller.com by becoming a sponsor. Any amount is appreciated!