> 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-pdf-to-image.md).

# PDF to Image Showcase Demo Code Sample

Convert PDFs to images like JPG or PNG.

{% 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://showcase.apryse.com/pdf-to-image" class="button primary">Live demo</a>
{% endhint %}

Easily convert PDFs to images like JPG or PNG, completely on the client side, with no server needed.

This demo allows you to:

* Upload your own PDF file
* Add annotations
* Convert the PDF's first page into an image
* Download the image

**Implementation steps** To add form fields to a PDF with WebViewer:

Step 1: Choose your [preferred web stack](/web/get-started/readme.md) Step 2: Add the ES6 JavaScript sample code provided in this guide

This demo converts only the first page of the PDF.

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" %}

<pre class="language-js" data-line-numbers><code class="lang-js">// ES6 Compliant Syntax
// GitHub Copilot v1, Claude Sonnet 3.5, 2025-07-31
// File: pdf-to-image/index.js
 
import WebViewer from '@pdftron/webviewer';
import { saveAs } from 'file-saver';

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

// List of supported image formats
 const imageFormats = [ 'jpeg', 'png'];

const element = document.getElementById('viewer');
let theInstance = null;
const onLoad = async (instance) => {
  theInstance = instance;
  instance.Core.documentViewer.addEventListener('documentLoaded', () => {
    toDownload = null; // reset download state
    buttonDownload.style.display = 'none'; // hide download button when uploading new file
  });
};

// Initialize WebViewer and load default document
WebViewer(
  {
    path: '/lib',
    licenseKey: licenseKey, 
    initialDoc: 'https://apryse.s3.amazonaws.com/public/files/samples/WebviewerDemoDoc.pdf',
    enableFilePicker: true, // Enable file picker to open files. In WebViewer -> menu icon -> Open File
  },
  element
).then((instance) => {
  onLoad(instance);
});

let toDownload = null;

const buttonDownload = document.createElement('button');
buttonDownload.textContent = '';
buttonDownload.style.display = 'none'; // initially hide the download button
buttonDownload.onclick = async () => {
  if (toDownload) {
    const { blob, newFileName } = toDownload;
    saveAs(blob, newFileName);
  }
};

// Function to convert the current document to an image
// If the document has more than one page, it will convert the current page only
const convertToImage = async (format) => {
    const docViewer = theInstance.Core.documentViewer;
  const doc = docViewer.getDocument();
  const oldFileName = doc.getFilename();

  const newFileName = oldFileName.substring(0, oldFileName.lastIndexOf('.')) + '.' + format;
  console.log('Converting to:', newFileName);
  const pageNumber = docViewer.getCurrentPage();
  console.log('Current page:', pageNumber);
  const zoom = 2; // render at twice the resolution
  
  doc.loadCanvas({
    pageNumber,
    zoom,
    drawComplete: async (imageCanvas) => {
      const corePageRotation = (doc.getPageRotation(pageNumber) / 90) % 4;
      const annManager = docViewer.getAnnotationManager()
      annManager.setAnnotationCanvasTransform(imageCanvas.getContext('2d'), zoom, corePageRotation);

      // optionally comment out "drawAnnotations" below to exclude annotations
      await annManager.drawAnnotations(pageNumber, imageCanvas);
      imageCanvas.toBlob(function (blob) {
          toDownload = { blob, newFileName };
        }, 'image/' + format);
      buttonDownload.style.display = 'inline'; // show download button after conversion
      buttonDownload.textContent = newFileName + ' ⭳';
    }
  });
}

// Create a button to convert the current document to an image
const buttonConvert = document.createElement('button');
buttonConvert.textContent = 'Convert';
buttonConvert.onclick = async () => {
  const format = imageFormatSelect.value; // Get the selected image format
  await convertToImage(format);
};

// Create a dropdown for image formats
const imageFormatSelect = document.createElement('select');

// Populate the dropdown with options
imageFormats.forEach(format => {
  const option = document.createElement('option');
  option.value = format; // Use the format as the value
  option.textContent = format.toUpperCase(); // Display the format in uppercase
  imageFormatSelect.appendChild(option);
});

// set default value for the dropdown
imageFormatSelect.value = imageFormats[0]; // Default to first format
imageFormatSelect.onchange = () => {
  // Hide the download button when changing format
  buttonDownload.style.display = 'none';
  toDownload = null; // reset download state
};
const convertLabel = document.createElement('label');
convertLabel.textContent = 'Use the Open File command in the WebViewer UI menu to upload a PDF, then select image format: ';

// UI section
//
// Helper code to add controls to the viewer holding the buttons and dropdown

// Create a container for all controls (label, dropdown, and buttons)
const controlsContainer = document.createElement('div');

// Apply classes for styling using CSS
convertLabel.className = 'label-class';
buttonConvert.className = 'btn-style';
buttonDownload.className = 'btn-style';
imageFormatSelect.className = 'select-style';
controlsContainer.className = 'control-container';

// Append elements to the controls container
controlsContainer.appendChild(convertLabel);
controlsContainer.appendChild(imageFormatSelect);
controlsContainer.appendChild(buttonConvert);
controlsContainer.appendChild(buttonDownload);
element.insertBefore(controlsContainer, element.firstChild);

</code></pre>

[View the full sample on GitHub](https://github.com/ApryseSDK/webviewer-samples/tree/main/showcase-demos-playground)


---

# 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-pdf-to-image.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.
