Image to PDF Showcase Demo Code Sample

Requirements
View Demo

Easily convert images to PDF, entirely on the client side, with no server required. This follows the Image to PDF demo on showcase.

This demo allows you to:

  • Upload your own image format file (such as PNG, JPG, GIF, PNG, BMP, etc.)
  • Add customized annotations
  • Edit the layout and content
  • Download the updated PDF

Implementation steps

To add image format conversion to PDF with WebViewer:
Step 1: Get started with WebViewer in your preferred web stack
Step 2: Add the ES6 JavaScript sample code provided in this guide

1// ES6 Compliant Syntax
2// GitHub Copilot - GPT-4 - July 21, 2025
3// File: index.js
4
5import WebViewer from '@pdftron/webviewer';
6import saveAs from 'file-saver';
7
8// Customize the WebViewer UI
9const customizeUI = (instance) => {
10 const { UI } = instance;
11
12 // Set the toolbar group to the annotate tools
13 UI.setToolbarGroup('toolbarGroup-Annotate');
14
15 // Convert button
16 const convertButton = new UI.Components.CustomButton({
17 dataElement: 'convertToPdfButton',
18 className: 'custom-button-class',
19 label: 'Image to PDF',
20 onClick: () => convert(instance), // convert the image to PDF
21 style: {
22 padding: '10px 10px',
23 backgroundColor: 'blue',
24 color: 'white',
25 }
26 });
27
28 const defaultHeader = UI.getModularHeader('default-top-header');
29 defaultHeader.setItems([...defaultHeader.items, convertButton]);
30};
31
32// convert the image to PDF
33const convert = async (instance) => {
34
35 // Get the document
36 const document = instance.Core.documentViewer.getDocument();
37
38 // Get the filename
39 let fileName = document.getFilename();
40
41 // Ensure it ends with .pdf. If not, replace it with .pdf extension
42 if (!fileName.endsWith('.pdf'))
43 fileName = fileName.replace(/\.[^/.]+$/, '') + '.pdf';
44
45 try {
46 const data = await document.getFileData({
47 downloadType: 'pdf',
48 });
49
50 const arr = new Uint8Array(data);
51 const blob = new Blob([arr], { type: 'application/pdf' });
52
53 // Save the image as a PDF
54 saveAs(blob, fileName);
55
56 } catch (e) {
57 console.error('❌ Conversion failed:', e);
58 }
59};
60
61WebViewer(
62 {
63 path: '/lib',
64 initialDoc: 'https://apryse.s3.us-west-1.amazonaws.com/public/files/samples/Vancouver_komal-brar.jpg',
65 enableFilePicker: true, // Enable file picker to open files. In WebViewer -> menu icon -> Open File
66 licenseKey: 'YOUR_LICENSE_KEY',
67 },
68 document.getElementById('viewer')
69).then((instance) => {
70
71 // customize WebViewer UI
72 customizeUI(instance);
73
74 console.log('✅ WebViewer loaded successfully.');
75}).catch((error) => {
76 console.error('❌ Failed to initialize WebViewer:', error);
77});

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales