React PDF viewer
v1.4.0

Example: Create a simple toolbar

The toolbar can be customized via the layout.toolbar parameter. It is a function which has the following signature:

(ToolbarSlot => React.ReactElement) => React.ReactElement

You can look at the layouts/defaultToolbar.tsx file to see how the default toolbar is made.

In the following example, we will create a toolbar with the parts below:

  • The button to go to the previous page
  • The current page of the total number of pages
  • The button to go to the next page
  • The zoom out button
  • Display the current zoom level
  • The zoom in button

By taking the advantage of the CSS flexbox, we can layout the toolbar as following:

const renderToolbar = (toolbarSlot: ToolbarSlot): React.ReactElement => {
    return (
        <div
            style={{
                alignItems: 'center',
                display: 'flex',
                width: '100%',
            }}
        >
            <div
                style={{
                    alignItems: 'center',
                    display: 'flex',
                    flexGrow: 1,
                    flexShrink: 1,
                    justifyContent: 'center',
                }}
            >
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.previousPageButton}
                </div>
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.currentPage + 1} / {toolbarSlot.numPages}
                </div>
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.nextPageButton}
                </div>
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.zoomOutButton}
                </div>
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.zoomPopover}
                </div>
                <div style={{ padding: '0 2px' }}>
                    {toolbarSlot.zoomInButton}
                </div>
            </div>
        </div>
    );
};

The layout is kept as default which is defined by defaultLayout function:

import { defaultLayout } from '@phuocng/react-pdf-viewer';

const layout = (
    isSidebarOpened: boolean,
    container: Slot,
    main: Slot,
    toolbar: RenderToolbar,
    sidebar: Slot,
): React.ReactElement => {
    return defaultLayout(
        isSidebarOpened,
        container,
        main,
        toolbar(renderToolbar),
        sidebar,
    );
};

Now, the viewer with customized toolbar can be called as following

<Viewer
    fileUrl="..."
    layout={layout}
/>

Here is how the viewer looks like in action:

(The sample code)

1 / 8
90%