> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/showcase-demo-create-thumbnail.md).

# Create Thumbnail Showcase Demo Code Sample

Easily create high resolution thumbnail images from selected document pages.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://apryse.com/capabilities#PageManipulation" class="button primary">Package: Page Manipulation</a><a href="https://showcase.apryse.com/create-thumbnail" class="button primary">Live demo</a>
{% endhint %}

Easily create high resolution thumbnail images from selected document pages.

This demo allows you to:

* Choose your own document file.
* Create high-resolution thumbnails.
* Define PNG or JPEG image format.
* Specify scale factor \[0.1, 10], where low values yield smaller thumbnail sizes .

**Implementation steps**

To add Thumbnail Creation capability with WebViewer: Step 1: [Get started with WebViewer](/web/get-started/readme.md) in your preferred web stack. Step 2: Add the ES6 JavaScript sample code provided in this guide.

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

{% tabs %}
{% tab title="index.js" %}

<pre class="language-js" data-line-numbers><code class="lang-js">// ES6 Compliant Syntax
// GitHub Copilot v1.0, GPT-4.1, October 15, 2025
// File: index.js

import WebViewer from '@pdftron/webviewer';

const licenseKey = '<code class="expression">visitor.claims.wvKey || "YOUR_WEBVIEWER_LICENSE_KEY"</code>';

// Create Thumbnail Demo
// This code demonstrates how to create a high resolution JPG or PNG thumbnail for a PDF document using the loadCanvas API.

function initializeWebViewer() {

    // This code initializes the WebViewer with the basic settings
    WebViewer({
        path: '/lib',
        licenseKey: licenseKey,
        enableFilePicker: true,
        loadAsPDF: true, // Ensure files are loaded as PDF documents for best thumbnail quality
    }, document.getElementById('viewer')).then((instance) => {
        // Enable the measurement toolbar so it appears with all the other tools, and disable Cloudy rectangular tool
        const cloudyTools = [
            instance.Core.Tools.ToolNames.CLOUDY_RECTANGULAR_AREA_MEASUREMENT,
            instance.Core.Tools.ToolNames.CLOUDY_RECTANGULAR_AREA_MEASUREMENT2,
            instance.Core.Tools.ToolNames.CLOUDY_RECTANGULAR_AREA_MEASUREMENT3,
            instance.Core.Tools.ToolNames.CLOUDY_RECTANGULAR_AREA_MEASUREMENT4,
        ];
        instance.UI.enableFeatures([instance.UI.Feature.Measurement, instance.UI.Feature.Initials]);
        instance.UI.disableTools(cloudyTools);
        // Set default toolbar group to Annotate
        instance.UI.setToolbarGroup('toolbarGroup-Annotate');
        // Set default tool on mobile devices to Pan.
        if (UIElements.isMobileDevice()) {
            instance.UI.setToolMode(instance.Core.Tools.ToolNames.PAN);
        }

        instance.Core.documentViewer.addEventListener('documentUnloaded', () => {
            if (searchParams.has('file')) {
                searchParams.delete('file');
                history.replaceState(null, '', '?' + searchParams.toString());
            }
        });

        instance.Core.annotationManager.enableAnnotationNumbering();
        instance.UI.NotesPanel.enableAttachmentPreview();
        // Add the demo-specific functionality
        customizeUI(instance).then(() => {
            // Create UI controls after demo is initialized
            UIElements.createUIControls(instance);
        });
    });
}

const searchParams = new URLSearchParams(window.location.search);
const history = window.history || window.parent.history || window.top.history;

window.pageNum = 1;
window.scaleNum = 1.0;
window.thumbnailName = 'thumbnail';
window.thumbnailType = 'png';

window.thumbnailOptions = ['PNG', 'JPEG'];


const customizeUI = async (instance) => {
    // Load the default document
    await instance.UI.loadDocument('https://apryse.s3.us-west-1.amazonaws.com/public/files/samples/WebviewerDemoDoc.pdf');
};

// Function to handle the Create Thumbnail button click
window.onThumbnailButtonClick = (instance) => {
    // Get the document
    const doc = instance.Core.documentViewer.getDocument();

    // Get the page number from user input
    let pageNumber = parseInt(window.pageNum, 10);

    // Validate page number
    if (isNaN(pageNumber) || pageNumber &#x3C; 1 || pageNumber > doc.getPageCount()) {
        alert('Please enter a valid page number between 1 and ' + doc.getPageCount());
        return; // Exit if page number is invalid
    }

    // Clamp the page number to valid range
    pageNumber = isNaN(pageNumber) ? 1 : Math.min(Math.max(pageNumber, 1), doc.getPageCount());

    // Get the scale (zoom level) from user input
    const zoom = parseFloat(window.scaleNum);
    if (isNaN(zoom) || zoom &#x3C;= 0 || zoom > 10) {
        alert('Please enter a valid zoom level between 0.1 and 10');
        return; // Exit if zoom is invalid
    }
    
    // Compensate for device pixel ratio to ensure consistent output across devices
    // Normalize to standard DPR of 1.0 by dividing by actual DPR
    const devicePixelRatio = window.devicePixelRatio || 1;
    const adjustedZoom = zoom / devicePixelRatio;
    
    console.log(`Device Pixel Ratio: ${devicePixelRatio}`);
    console.log(`Original zoom: ${zoom}, Adjusted zoom: ${adjustedZoom}`);
    console.log(`This should produce thumbnails equivalent to DPR=1.0 environment`);

    // Get the file name and type from user input
    const name = window.thumbnailName;
    const type = window.thumbnailType;

    // Save to blob using the loadCanvas API
    doc.loadCanvas({
        pageNumber,
        zoom: adjustedZoom, // Use DPI-adjusted zoom for consistent output
        drawComplete: async (thumbnail) => {
            // Optionally, comment out "drawAnnotations" to exclude annotations
            await instance.Core.documentViewer
                .getAnnotationManager()
                .drawAnnotations(pageNumber, thumbnail);
            // thumbnail is a HTMLCanvasElement or HTMLImageElement
            thumbnail.toBlob(
                (blob) => {
                    saveAs(blob, name + '.' + type);
                },
                'image/' + type,
                1
            );
        },
    });
};

// Cleanup function for when the demo is closed or page is unloaded
const cleanup = (instance) => {
    if (typeof instance !== 'undefined' &#x26;&#x26; instance.UI) {
        if (instance.Core.documentViewer.getDocument()) {
            // Insert any other cleanup code here
        }
        console.log('Cleaning up demo');
    }
};

// Register cleanup for page unload
window.addEventListener('beforeunload', () => cleanup(instance));
window.addEventListener('unload', () => cleanup(instance));

// UI Elements Script Loader
// Loads the ui-elements.js script
function loadUIElementsScript() {
    return new Promise((resolve, reject) => {
        if (window.UIElements) {
            console.log('UIElements already loaded');
            resolve();
            return;
        }
        const script = document.createElement('script');
        script.src = '/showcase-demos/create-thumbnail/ui-elements.js';
        script.onload = function () {
            console.log('✅ UIElements script loaded successfully');
            resolve();
        };
        script.onerror = function () {
            console.error('Failed to load UIElements script');
            reject(new Error('Failed to load ui-elements.js'));
        };
        document.head.appendChild(script);
    });
}

// Load UIElements script first, then initialize WebViewer
loadUIElementsScript().then(() => {
    initializeWebViewer();
}).catch((error) => {
    console.error('Failed to load UIElements:', error);
});

</code></pre>

{% endtab %}

{% tab title="ui-elements.js" %}
{% code title="ui-elements.js" lineNumbers="true" %}

```js
// ES6 Compliant Syntax
// GitHub Copilot v1.0, GPT-4.1, October 15, 2025
// File: ui-elements.js

// UI Elements class to create and manage custom UI controls
//
// Helper code to add controls to the viewer holding the buttons
// This code creates a container for the buttons, styles them, and adds them to the viewer
//
class UIElements {
    // Function to check if the user is on a mobile device
    static isMobileDevice = () => {
        return (
            /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
                window.navigator.userAgent
            ) ||
            /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
                window.navigator.userAgent.substring(0, 4)
            )
        );
    }

    // Create and return the page number input field
    static pageNumberInputField = () => {
        // Create a container for the input field
        const container = document.createElement('div');
        container.className = 'input-container';
        container.style.display = 'flex';

        // Create and append the label
        const label = document.createElement('label');
        label.className = 'input-label';
        label.textContent = 'Page Number';
        container.appendChild(label);

        // Create and append the input field
        const input = document.createElement('input');
        input.className = 'number-input-field';
        input.type = 'number';
        input.value = window.pageNum;
        input.onchange = (e) => {
            window.pageNum = e.target.value;
        };
        input.min = 1;
        input.pattern = "\d+";
        container.appendChild(input);

        return container;
    }

    // Create and return the scale factor input field
    static scaleFactorInputField = () => {
        // Create a container for the input field
        const container = document.createElement('div');
        container.className = 'input-container';

        // Create and append the label
        const label = document.createElement('label');
        label.className = 'input-label';
        label.textContent = 'Scale Factor';
        container.appendChild(label);

        // Create and append the input field
        const input = document.createElement('input');
        input.className = 'number-input-field';
        input.type = 'number';
        input.value = window.scaleNum;
        input.onchange = (e) => {
            window.scaleNum = e.target.value;
        }
        input.min = 0.1;
        input.step = 0.1;
        input.max = 10;
        container.appendChild(input);

        return container;
    }

    // Create and return the file name input field
    static fileNameInputField = () => {
        // Create a container for the input field
        const container = document.createElement('div');
        container.className = 'input-container';

        // Create and append the label
        const label = document.createElement('label');
        label.className = 'input-label';
        label.textContent = 'File Name';
        container.appendChild(label);

        // Create and append the input field
        const input = document.createElement('input');
        input.className = 'text-input-field';
        input.type = 'text';
        input.value = window.thumbnailName;
        input.onchange = (e) => {
            window.thumbnailName = e.target.value;
        };
        input.required = true;
        input.minLength = 1;
        container.appendChild(input);

        return container;
    }

    // Create and return the image type dropdown field
    static imageTypeInputField = () => {
        // Create a container for the dropdown
        const container = document.createElement('div');
        container.className = 'input-container';

        // Create and append the label
        const label = document.createElement('label');
        label.className = 'input-label';
        label.textContent = 'Image Type';
        container.appendChild(label);

        // Create and append the dropdown
        const select = document.createElement('select');
        select.className = 'dropdown-input-field';
        select.value = window.thumbnailType;
        select.onchange = (e) => {
            window.thumbnailType = e.target.value;
        };

        // Add options to the dropdown
        window.thumbnailOptions.forEach((option) => {
            const optionElement = document.createElement('option');
            optionElement.value = option.toLowerCase();
            optionElement.textContent = option;
            select.appendChild(optionElement);
        });
        container.appendChild(select);

        return container;
    }

    // Create and return the download button
    static downloadButton = (instance) => {
        // Create the button element
        const button = document.createElement('button');
        button.className = 'button';
        button.textContent = 'Download Thumbnail';
        button.onclick = () => window.onThumbnailButtonClick(instance);

        return button;
    }

    static createUIControls = (instance) => {
        // Create a container for all controls
        const controlsContainer = document.createElement('div');
        controlsContainer.className = 'controls-container';

        controlsContainer.appendChild(this.pageNumberInputField());
        controlsContainer.appendChild(this.scaleFactorInputField());
        controlsContainer.appendChild(this.fileNameInputField());
        controlsContainer.appendChild(this.imageTypeInputField());
        controlsContainer.appendChild(this.downloadButton(instance));

        // Add the controls container to the viewer element
        const element = document.getElementById('viewer');
        element.insertBefore(controlsContainer, element.firstChild);

        console.log('✅ UI controls created');
    };
}

// Make UIElements globally available
window.UIElements = UIElements;
```

{% endcode %}
{% endtab %}

{% tab title="index.css" %}
{% code title="index.css" lineNumbers="true" %}

```css
/* CSS standard Compliant Syntax */
/* GitHub Copilot v1.0, GPT-4.1, October 15, 2025 */
/* File: index.css */

/* Button Styles */
.button {
    background-color: #007bff;
    margin: 0 10px;
    padding: 5px 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    color: white;
}

.button:hover {
    background-color: #0056b3;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.button:active {
    transform: translateY(1px);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

/* Text Inputs Container */
.text-inputs-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 10px;
}

/* Input Controls */
.input-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 15px;
}

.input-label {
    display: block;
    text-align: start;
    font-size: 14px;
    margin-inline-end: 12px;
    margin-bottom: 8px;
    font-weight: bold;
    transition: background-color border-color color fill stroke opacity box-shadow transform;
    transition-duration: 200ms;
    opacity: 1;
    color: #485056;
    line-height: 1.5;
    width: 50%;
    white-space: nowrap;
}

.number-input-field,
.text-input-field, 
.dropdown-input-field {
    width: 100%;
    min-width: 0px;
    outline: transparent solid 2px;
    outline-offset: 2px;
    position: relative;
    appearance: none;
    transition: background-color border-color color fill stroke opacity box-shadow transform;
    transition-duration: 200ms;
    border-radius: 6px;
    background-color: white;
    color: #485056;
    border-width: 1px;
    border-style: solid;
    border-image: initial;
    border-color: #cfd4da;
    box-sizing: border-box;
    font-size: 14px;
    padding-inline-start: 16px;
    padding-inline-end: 16px;
    height: 40px;
}

.number-input-field:focus,
.text-input-field:focus,
.dropdown-input-field:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

/* Controls Container */
.controls-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 15px;
    margin: 5px 0;
    padding: 16px;
    padding-bottom: 5px;
    border-bottom: 1px solid #DFE1E6;
    background-color: rgba(112, 198, 255, 0.2);
}


```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/showcase-demo-create-thumbnail.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
