interface ExportNodeAsImageParams {
nodeId: string;
format?: "PNG" | "JPG" | "SVG" | "PDF";
scale?: number;
}
/**
* Export a node as an image
*/
export async function exportNodeAsImage(
params: ExportNodeAsImageParams,
): Promise<{
imageData: string;
mimeType: string;
}> {
const { nodeId, format = "PNG", scale = 1 } = params;
const node = await figma.getNodeByIdAsync(nodeId);
if (!node) {
throw new Error(`Node not found with ID: ${nodeId}`);
}
if (!("exportAsync" in node)) {
throw new Error(`Node cannot be exported: ${nodeId}`);
}
const exportable = node as SceneNode;
let mimeType: string;
let settings: ExportSettings;
switch (format.toUpperCase()) {
case "PNG":
settings = { format: "PNG", constraint: { type: "SCALE", value: scale } };
mimeType = "image/png";
break;
case "JPG":
case "JPEG":
settings = { format: "JPG", constraint: { type: "SCALE", value: scale } };
mimeType = "image/jpeg";
break;
case "SVG":
settings = { format: "SVG" };
mimeType = "image/svg+xml";
break;
case "PDF":
settings = { format: "PDF" };
mimeType = "application/pdf";
break;
default:
settings = { format: "PNG", constraint: { type: "SCALE", value: scale } };
mimeType = "image/png";
}
const bytes = await exportable.exportAsync(settings);
// Convert to base64
const imageData = figma.base64Encode(bytes);
return {
imageData,
mimeType,
};
}