5. Render all artboards as PNGs
Now let's write a new API Endpoint to export all artboards as PNGs. We'll iterate on the code we wrote for
artboards.js and add some extra logic to render the artboards.
previews.jsfile in the
apifolder with the following contents:
Call the new API endpoint by going to
http://localhost:3000/api/previews?designId=YOUR_DESIGN_ID. Once it finishes, you should see lots of generated images in the
Nice 🎉. The script works, but there are some optimizations we can make.
Optimization 1: Global font fallback
Text layers may be missing in artboards if you run the script in an environment where there aren't any fonts (for example, in CodeSandbox). To handle this, we'll create a global fonts fallback. This means that even if we don't have the exact font specified in the design, we'll at least see a replacement.
Let's do it:
Create a folder in the root of the project called
Download a great universal open font to use as the fallback font. We recommend using Inter made by Rasmus Andersson. Download the zip and extract it. We'll use the fonts in the "Inter Desktop" directory.
Drag the desired fonts the new
fontsfolder. The contents of the fonts folder should look something like this:
Add these two lines of code to
previews.jsto set up the font directory and the global fallback font:
previews.jsnow looks like this:
previewendpoint again and you should see the rendered artboards with the text.☝️If you had the text layers rendered before, it's because the SDK automatically found fonts on your local computer and set the fallback font to one of those. When running in production, you'll need to configure the fallback fonts like we did in this step.
Optimization 2: Organizing and caching artboard previews
Design Viewer can process multiple designs, so it would be best to store previews in folders based on the design ID.
Also, if we call the
preview API endpoint multiple times, the artboards will be rendered each time. It should skip designs that have already been rendered.
Let’s solve both of these issues:
Use the Node.js
fsmodule to check whether there is a folder called
publicfolder. If it doesn't exist, create it.
Next, we'll store rendered images to
/public/images/:designID/. If a folder with the design ID already exists, we'll assume that the previously rendered files are intact.
The final code for
previews.jslooks like this:
previewendpoint again and you should see this file structure as a result:
That was it for this lesson. As always, you can see the ongoing result in the CodeSandbox below.
Was this article helpful?