Skip to main content
The best way to learn how to build custom components is to see them in action. This guide walks through a complete example of building a PDF display component from scratch.

Case study: A component to display PDFs

Let’s work through an example of building a custom Gradio component for displaying PDF files. This component will come in handy for showcasing document question answering models, which typically work on PDF input. This is a sneak preview of what our finished component will look like: PDF Display Demo

Prerequisites

Make sure you have:

Step 1: Create the custom component

Navigate to a directory of your choosing and run:
This will create a subdirectory called pdf with the following structure:

Step 2: Add JavaScript dependencies

We’re going to use the pdfjs library to display PDFs in the frontend. From within the frontend directory, run:
Your package.json should now include these dependencies:

Step 3: Launch the dev server

Run the dev command to launch the development server:
You should see a link printed to your console:
Click on that link to see your component in action. Changes to the frontend and backend will reflect instantaneously!

Step 4: Build the frontend skeleton

In Index.svelte, add the following imports and props:
The gradio object contains metadata about the application and utility methods. We define that our component will dispatch change and upload events.

Add the upload UI

Replace the content below the </script> tag with:

Step 5: Add PDF rendering logic

Import pdfjs and set up the worker:
Add the rendering functions:
The $: syntax in Svelte is how you declare reactive statements. Whenever any of the inputs change, Svelte will automatically re-run that statement.
Add the canvas element:

Step 6: Handle file upload and clear

Add event handlers:
Connect them to the Upload components:

Step 7: Add page navigation

Import the button component and add navigation functions:
Add the button UI:

Step 8: Implement the backend

In your component’s Python file, update the code to:

Step 9: Build and publish

Build your component:
This creates a .whl file in the dist/ directory that anyone can install with pip install <path-to-whl>. Publish to PyPI and HuggingFace Spaces:

Conclusion

You’ve built a complete custom component! You can now use it in any Gradio 4.0+ app:

More examples

Explore this collection of custom components on the HuggingFace Hub to learn from other developers’ code. Need help? Join the Gradio community on the HuggingFace Discord.