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