Save JS file to Media

What I’m trying to do:
Hi There,

  • Take a Snapshot from the GUI
  • Download the Snapshot as SVG in Client
  • Convert the JS SVG File to Media and Save it in the Table
  • The Snapshot needs to be integrated into a PDF

What I’ve tried and what’s not working:

  • The file saved in the Table shows errors
  • Like: This page contains the following errors: error on line 1 at column 1: Start tag expected, ‘<’ not found

Any Idea ? :roll_eyes:

Clone link:
share a copy of your app

If you print out your b64string, you’ll see it starts like this:

data:image/svg+xml;charset=utf-8,<svg xmlns=

This is (in my experience) common when you get image strings from Javascript. You need to strip off the part before the first <, since that isn’t part of the actual SVG image, it’s just information about the rest of the string.

Something like this works, but is pretty fragile (you’d actually want to look for the < and strip off everything in front of it):

b64string = b64string[len('data:image/svg+xml;charset=utf-8,'):]

After that, you need to create your BlobMedia from that string, not from the URL. Something more like:

my_media = anvil.BlobMedia(content_type="image/svg", content=b64string.encode('utf-8'), name="image.svg")

That way your BlobMedia contains the actual SVG image, not just the URL of it.

1 Like

@jshaffstall

appreciate the fast support :slight_smile:
Got it, the image is now created but with some errors inside.
Is there another way to get the JS Snapshot inside the Client or Server?

Other than calling out to Javascript? Not that I know of. You could narrow it down to smaller elements (e.g. just the content panel) by changing what you pass into get_dom_node.

OK, what about creating a png?
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACIsAAAKjCA

You’re still going to need to remove the prefix. What remains is presumably base64 encoded text. You’d do something like this to get the bytes back out of it:

BlobMedia('image/png', base64.b64decode(base64str))
1 Like

@jshaffstall

done :ok_hand: thank you!
The result of the .png File is perfect in the BlobMedia
Attached the code:

    def button_1_click(self, **event_args):
        # Create Snapshot and Download in Browser
        import anvil.media
        b64string=anvil.js.window.domtoimage.toPng(anvil.js.get_dom_node(self))
        a=document.createElement("a")
        a.href=b64string
        a.download='Snapshot.png'
        a.click()
        
        # Decode JS Snapshot to BlobMedia and save in Table
        import base64
        base64str = b64string[len('data:image/png;base64,'):]
        print(base64str)
        my_media = anvil.BlobMedia(content_type="image/png", content=base64.b64decode(base64str), name="image.png")
        app_tables.file.get(file_name="image").update(file = my_media)
        print(b64string)
        pass

2 Likes