Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

File export

Hooks & Utilities

File export TypeScript helper for React

Date utilsFile types
Live props
Options
scale2x
background
fileName
  1. Home
  2. Components
  3. Hooks & Utilities
  4. File export
Pro

File export TypeScript helper for React

v1.0.0·Added in 1.0.0

File export helpers for React apps: download blobs, text and JSON, turn a canvas or an SVG into a PNG, copy images and name files cleanly.

The card is an SVG. Download SVG saves it as it is, Download PNG rasterizes it at the playground scale (with the background color when one is set), Copy PNG puts the image on the clipboard (paste it into a chat or a doc), and Download JSON saves the card's data. Every file is named from the title plus the local date and time, and the readout shows the last name and size.

File export is a Pro React helper in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add file-export.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add file-export

File export is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import downloadBlob from @/lib/file-export.

import { svgToImageBlob, downloadBlob, timestampedFileName } from "@/lib/file-export"

export function DownloadQr({ svg }: { svg: SVGSVGElement | null }) {
  return (
    <button
      type="button"
      onClick={async () => {
        if (!svg) return
        const png = await svgToImageBlob(svg, { scale: 4, background: "#ffffff" })
        downloadBlob(png, timestampedFileName("invoice-qr-code", "png"))
      }}
    >
      Download PNG
    </button>
  )
}

API

  • scaledefault 2
    number

    svgToImageBlob(svg, { scale }): device pixels per CSS pixel of the PNG. 2 keeps exports sharp on retina screens and in print.

  • backgrounddefault ""
    string

    svgToImageBlob(svg, { background }): a fill behind the image; empty keeps the PNG transparent.

  • fileNamedefault "Certificate Emma Carter"
    string

    The base passed to timestampedFileName(base, extension): diacritics and unsafe characters are removed, the local date and time are appended.

  • downloadBlob
    (blob: Blob, filename: string) => void

    The main helper: saves a Blob under a file name through a temporary object URL, released right after. Browser only; call it from an event handler, never during render.

Parts

  • downloadUrl

    function

    Saves a URL (same origin, or a data: or blob: URL) under a file name through a temporary link. Browser only, for event handlers.

  • downloadText

    function

    Saves text such as a log, a diff or a CSV under a file name. Options: type (default text/plain) and bom, which prefixes a UTF-8 BOM so Excel on Windows reads accented letters.

  • downloadJson

    function

    Saves any value as pretty-printed JSON (2 spaces by default) under a file name.

  • canvasToBlob

    function

    canvas.toBlob as a promise for PNG, JPEG or WebP. Rejects when a cross-origin image has tainted the canvas.

  • serializeSvg

    function

    Standalone SVG text from an element or a string, with the namespaces and XML header added so the file opens in any viewer.

  • svgToBlob

    function

    The same standalone SVG as an image/svg+xml Blob, ready for downloadBlob.

  • svgToImageBlob

    function

    Draws an SVG into a canvas and returns a PNG, JPEG or WebP Blob: QR codes, signatures, charts. Options: width, height, scale (default 2), background, type, quality. The size defaults to the SVG's own width, height or viewBox.

  • loadImage

    function

    An image ready for drawImage from a URL, a data URL or a File or Blob; an object URL is released once the image decodes. Croppers and avatar uploads use it.

  • blobToDataUrl

    function

    A data: URL from a Blob, for previews and small uploads.

  • canCopyImages

    function

    Whether this browser can put an image on the clipboard (ClipboardItem and clipboard.write exist). Check it in an effect or a handler and hide the Copy button when it is false.

  • copyImageToClipboard

    function

    Puts a PNG on the clipboard. Pass the promise itself from the click handler, not an awaited blob: Safari only allows the write when the clipboard item is created inside the gesture. Resolves false when unsupported or denied.

  • shareFile

    function

    Opens the phone's share sheet with a file, title and text. Resolves false where files cannot be shared, so the caller can download instead.

  • sanitizeFileName

    function

    Strips what file systems refuse and keeps names readable: "Invoice #12/2026" becomes "Invoice-12-2026", "Café menu" becomes "Cafe-menu". Falls back to "file" when nothing is left.

  • timestampedFileName

    function

    A clean base name plus the local date and time, so repeated exports never collide: ("Signature", "png") gives "Signature-2026-09-24-1640.png".

  • ImageType

    type

    "image/png" | "image/jpeg" | "image/webp", the raster formats the helpers produce.

  • RasterizeOptions

    type

    svgToImageBlob's options: width, height, scale, background, type, quality.

Examples

Clean file names

sanitizeFileName strips what file systems refuse; the timestamp keeps exports from colliding.

Export a report

downloadText with a BOM for Excel, and downloadJson for the same rows.

Copy a chart

copyImageToClipboard with the rasterize promise passed straight from the click.

Dependencies

No dependencies beyond React.

Files

  • lib/file-export.ts

FAQ

Is the File export helper free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install File export?

Run npx wingo-ui@latest add file-export. With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/file-export.

See also

useClipboardhookFile typeslibSpreadsheetlib

Used in

QR CodeAvatar UploadImage CropperAudio PlayerSignature PadJSON ViewerLog ViewerAutomation Builder PageSettings PageUsers Admin Page

More React hooks and utilities

FilterslibForm validationlibHapticslibInvoicinglibMotion presetslibNavigationlib
All 36 React hooks and utilities

Articles using this component

  • React QR Code with Logo: Rounded Modules, PNG and SVG

    Component guides · Oct 19, 2026 · 9 min read

  • React Signature Pad: Smooth Ink, Typed Mode, PNG and SVG

    Component guides · Oct 16, 2026 · 9 min read

PreviousDate utilsNext File types
NORTHWIND ACADEMYCertificate of completionEmma Cartercompleted the course "E-invoicing basics"8 hours · New YorkSep 24, 2026No. NA-2026-0412

scale 2x · transparent