In index.html, create an input element for the license key and a button to activate the SDK:
Implement the activation logic in main.js:
async function activate(license) { try { Dynamsoft.DDV.Core.license = license; Dynamsoft.DDV.Core.engineResourcePath = \\\"https://cdn.jsdelivr.net/npm/[email protected]/dist/engine\\\"; await Dynamsoft.DDV.Core.init(); Dynamsoft.DDV.setProcessingHandler(\\\"imageFilter\\\", new Dynamsoft.DDV.ImageFilter()); docManager = Dynamsoft.DDV.documentManager; } catch (error) { console.error(error); toggleLoading(false); }}
Explanation
The Dynamsoft Document Viewer SDK provides a built-in document editor that requires minimal code to construct a web PDF viewer application.
Create a container element for the document viewer in index.html:
","image":"http://www.luping.net/uploads/20241119/1731991338673c172aa2afc.png","datePublished":"2024-11-19T13:47:08+08:00","dateModified":"2024-11-19T13:47:08+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}Initialize the document viewer in main.js:
async function showViewer() { if (!docManager) return; let editContainer = document.getElementById(\\\"edit-viewer\\\"); editContainer.parentNode.style.display = \\\"block\\\"; editViewer = new Dynamsoft.DDV.EditViewer({ container: editContainer, uiConfig: DDV.getDefaultUiConfig(\\\"editViewer\\\", { includeAnnotationSet: true }) });}The uiConfig parameter specifies the default UI configuration for the document viewer, including annotation tools.
Step 4: Add a Custom Button to Insert Barcodes into the PDF Document
Dynamsoft Document Viewer allows for customization of UI elements and event handlers. According to the official documentation, you can add custom buttons.
A Custom Barcode Button with Google\\'s Material Icons
Define a custom button object in main.js:
const qrButton = { type: Dynamsoft.DDV.Elements.Button, className: \\\"material-icons icon-qr_code\\\", tooltip: \\\"Add a QR code. Ctrl Q\\\", events: { click: \\\"addQr\\\", },};The className points to Google fonts. Use the material-icons class to display the qr_code icon in the button.
Add the Barcode Button to the Toolbar
To add the button to the toolbar, modify the uiConfig parameter in the showViewer function:
const pcEditViewerUiConfig = { type: Dynamsoft.DDV.Elements.Layout, flexDirection: \\\"column\\\", className: \\\"ddv-edit-viewer-desktop\\\", children: [ { type: Dynamsoft.DDV.Elements.Layout, className: \\\"ddv-edit-viewer-header-desktop\\\", children: [ { type: Dynamsoft.DDV.Elements.Layout, children: [ Dynamsoft.DDV.Elements.ThumbnailSwitch, Dynamsoft.DDV.Elements.Zoom, Dynamsoft.DDV.Elements.FitMode, Dynamsoft.DDV.Elements.DisplayMode, Dynamsoft.DDV.Elements.RotateLeft, Dynamsoft.DDV.Elements.RotateRight, Dynamsoft.DDV.Elements.Crop, Dynamsoft.DDV.Elements.Filter, Dynamsoft.DDV.Elements.Undo, Dynamsoft.DDV.Elements.Redo, Dynamsoft.DDV.Elements.DeleteCurrent, Dynamsoft.DDV.Elements.DeleteAll, Dynamsoft.DDV.Elements.Pan, Dynamsoft.DDV.Elements.AnnotationSet, qrButton, ], }, { type: Dynamsoft.DDV.Elements.Layout, children: [ { type: Dynamsoft.DDV.Elements.Pagination, className: \\\"ddv-edit-viewer-pagination-desktop\\\", }, Dynamsoft.DDV.Elements.Load, { type: Dynamsoft.DDV.Elements.Button, className: \\\"ddv-button ddv-button-download\\\", events: { click: \\\"download\\\", } } ], }, ], }, Dynamsoft.DDV.Elements.MainView, ],};editViewer = new Dynamsoft.DDV.EditViewer({ container: editContainer, uiConfig: pcEditViewerUiConfig});Press the Button to Pop Up a Barcode Generation Dialog
When the barcode button is clicked, a pop-up dialog will appear for users to input the barcode content and select the barcode type:
editViewer.on(\\\"addQr\\\", addQr);The dialog contains the following elements:
- A dropdown list for selecting barcode types.
- An input field for entering barcode content.
- An OK button to submit the data.
- A Cancel button to close the pop-up without submitting.
Here\\'s the full code:
Step 5: Generate a Barcode and Insert it as Annotation to PDF Document
Include the bwip-js library in index.html. This library is used to generate barcodes in various formats, such as QR Code, PDF417, and DataMatrix.
After retrieving the barcode content and type, use bwipjs to draw the generated barcode on a canvas. Then, convert the canvas to a blob and insert it as an annotation to the PDF document.
if (barcodeContent !== null) { try { bwipjs.toCanvas(tempCanvas, { bcid: barcodeType, text: barcodeContent, scale: 3, includetext: false, }); tempCanvas.toBlob(async (blob) => { if (blob) { let currentPageId = docs[0].pages[editViewer.getCurrentPageIndex()]; let pageData = await docs[0].getPageData(currentPageId); const option = { stamp: blob, x: pageData.mediaBox.width - 110, y: 10, width: 100, height: 100, opacity: 1.0, flags: { print: false, noView: false, readOnly: false, } } if (applyToAllPages) { for (let i = 0; i < docs[0].pages.length; i ) { await Dynamsoft.DDV.annotationManager.createAnnotation(docs[0].pages[i], \\\"stamp\\\", option) } } else { await Dynamsoft.DDV.annotationManager.createAnnotation(currentPageId, \\\"stamp\\\", option) } } }, \\'image/png\\'); } catch (e) { console.log(e); }}Step 6: Save the PDF Document with Barcodes to Local Disk
Create a download() function and bind it to the download button in the toolbar:
editViewer.on(\\\"download\\\", download);async function download() { try { const pdfSettings = { saveAnnotation: \\\"flatten\\\", }; let blob = await editViewer.currentDocument.saveToPdf(pdfSettings); saveBlob(blob, `document_${Date.now()}.pdf`); } catch (error) { console.log(error); }}function saveBlob(blob, fileName) { const url = URL.createObjectURL(blob); const a = document.createElement(\\'a\\'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);}When saving the PDF document, the saveAnnotation option is set to flatten, ensuring that annotations, including the barcodes, are embedded in the document.
Running the Web PDF Document Editor
Start a web server in the root directory of your project:
python -m http.serverOpen http://localhost:8000 in your web browser.
Load a PDF document.
Insert a barcode as an annotation into the PDF document.
Reading Barcodes from PDF Documents
Once the PDF document is saved to your local disk, you can verify the barcode content by reading it with the Dynamsoft Barcode Reader.
Install barcode4nodejs, a Node.js wrapper built with the Dynamsoft C Barcode Reader SDK.
npm i barcode4nodejsCreate a script file, test.js, to read barcodes from the PDF document:
var dbr = require(\\'barcode4nodejs\\');var barcodeTypes = dbr.formats.ALL;dbr.initLicense(\\\"LICENSE-KEY\\\");let args = process.argv;if (args.includes(\\'-f\\')) { let fIndex = args.indexOf(\\'-f\\'); if (args[fIndex 1]) { (async function () { try { var result = await dbr.decodeFileAsync(args[fIndex 1], barcodeTypes, \\\"\\\"); console.log(result); setTimeout(() => { console.log(\\'terminated\\'); }, 1000); } catch (error) { console.log(error); } })(); } else { console.log(\\'Please add a file.\\'); }}Note: You need to replace the LICENSE-KEY with your own.
Run the script with the path to a PDF file:
node test.js -fThe barcode content will be printed in the console.
Source Code
https://github.com/yushulx/web-twain-document-scan-management/tree/main/examples/document_annotation
«Если рабочий хочет хорошо выполнять свою работу, он должен сначала заточить свои инструменты» — Конфуций, «Аналитики Конфуция. Лу Лингун»титульная страница > программирование > Как вставить штрих-коды в PDF-документ с помощью HTMLnd JavaScript
Как вставить штрих-коды в PDF-документ с помощью HTMLnd JavaScript
Опубликовано 19 ноября 2024 г.Просматривать:570
Inserting barcodes into PDF documents can significantly streamline document management, tracking, and data processing workflows. Barcodes serve as unique identifiers, enabling automated data entry, quick retrieval, and enhanced security. In this article, we'll demonstrate how to leverage HTML5, JavaScript, and the Dynamsoft Document Viewer SDK to generate and embed barcodes into PDF documents.
Web PDF Editor Demo Video
Online Demo
https://yushulx.me/web-document-annotation/
Prerequisites
Dynamsoft Document Viewer: This JavaScript SDK allows for seamless viewing and annotation of various document formats, including PDFs and common image files such as JPEG, PNG, TIFF, and BMP. With its robust feature set, you can render PDFs, navigate pages, enhance image quality, and save annotated documents. Install the package from npm to get started.
Dynamsoft Capture Vision Trial License: To access the full capabilities of the Dynamsoft SDKs, sign up for a 30-day free trial license. This trial offers complete access to all features, enabling you to explore the SDKs in-depth.
Steps to Implement a PDF Document Editor in HTML5 and JavaScript
In the following paragraphs, we'll walk you through the process of creating a web-based PDF document editor with barcode insertion capabilities. The editor will enable users to load PDF documents, insert barcodes as annotations, and save the modified PDF files locally.
Step 1: Include the Dynamsoft Document Viewer SDK
In the
section of your HTML file, add the following script tags to include the Dynamsoft Document Viewer SDK:
Step 2: Activate Dynamsoft Document Viewer
In index.html, create an input element for the license key and a button to activate the SDK:
Implement the activation logic in main.js:
async function activate(license) { try { Dynamsoft.DDV.Core.license = license; Dynamsoft.DDV.Core.engineResourcePath = "https://cdn.jsdelivr.net/npm/[email protected]/dist/engine"; await Dynamsoft.DDV.Core.init(); Dynamsoft.DDV.setProcessingHandler("imageFilter", new Dynamsoft.DDV.ImageFilter()); docManager = Dynamsoft.DDV.documentManager; } catch (error) { console.error(error); toggleLoading(false); } }Explanation
- The engineResourcePath must point to the location of the Dynamsoft Document Viewer engine files.
- setProcessingHandler sets the image filter for enhancing image quality.
- The documentManager object is used to manage the document viewer and editor.
Step 3: Create a Web PDF Viewer with Ready-to-Use Components
The Dynamsoft Document Viewer SDK provides a built-in document editor that requires minimal code to construct a web PDF viewer application.
Create a container element for the document viewer in index.html:
Initialize the document viewer in main.js:
async function showViewer() { if (!docManager) return; let editContainer = document.getElementById("edit-viewer"); editContainer.parentNode.style.display = "block"; editViewer = new Dynamsoft.DDV.EditViewer({ container: editContainer, uiConfig: DDV.getDefaultUiConfig("editViewer", { includeAnnotationSet: true }) }); }The uiConfig parameter specifies the default UI configuration for the document viewer, including annotation tools.
Step 4: Add a Custom Button to Insert Barcodes into the PDF Document
Dynamsoft Document Viewer allows for customization of UI elements and event handlers. According to the official documentation, you can add custom buttons.
A Custom Barcode Button with Google's Material Icons
Define a custom button object in main.js:
const qrButton = { type: Dynamsoft.DDV.Elements.Button, className: "material-icons icon-qr_code", tooltip: "Add a QR code. Ctrl Q", events: { click: "addQr", }, };The className points to Google fonts. Use the material-icons class to display the qr_code icon in the button.
Add the Barcode Button to the Toolbar
To add the button to the toolbar, modify the uiConfig parameter in the showViewer function:
const pcEditViewerUiConfig = { type: Dynamsoft.DDV.Elements.Layout, flexDirection: "column", className: "ddv-edit-viewer-desktop", children: [ { type: Dynamsoft.DDV.Elements.Layout, className: "ddv-edit-viewer-header-desktop", children: [ { type: Dynamsoft.DDV.Elements.Layout, children: [ Dynamsoft.DDV.Elements.ThumbnailSwitch, Dynamsoft.DDV.Elements.Zoom, Dynamsoft.DDV.Elements.FitMode, Dynamsoft.DDV.Elements.DisplayMode, Dynamsoft.DDV.Elements.RotateLeft, Dynamsoft.DDV.Elements.RotateRight, Dynamsoft.DDV.Elements.Crop, Dynamsoft.DDV.Elements.Filter, Dynamsoft.DDV.Elements.Undo, Dynamsoft.DDV.Elements.Redo, Dynamsoft.DDV.Elements.DeleteCurrent, Dynamsoft.DDV.Elements.DeleteAll, Dynamsoft.DDV.Elements.Pan, Dynamsoft.DDV.Elements.AnnotationSet, qrButton, ], }, { type: Dynamsoft.DDV.Elements.Layout, children: [ { type: Dynamsoft.DDV.Elements.Pagination, className: "ddv-edit-viewer-pagination-desktop", }, Dynamsoft.DDV.Elements.Load, { type: Dynamsoft.DDV.Elements.Button, className: "ddv-button ddv-button-download", events: { click: "download", } } ], }, ], }, Dynamsoft.DDV.Elements.MainView, ], }; editViewer = new Dynamsoft.DDV.EditViewer({ container: editContainer, uiConfig: pcEditViewerUiConfig });Press the Button to Pop Up a Barcode Generation Dialog
When the barcode button is clicked, a pop-up dialog will appear for users to input the barcode content and select the barcode type:
editViewer.on("addQr", addQr);The dialog contains the following elements:
- A dropdown list for selecting barcode types.
- An input field for entering barcode content.
- An OK button to submit the data.
- A Cancel button to close the pop-up without submitting.
Here's the full code:
Step 5: Generate a Barcode and Insert it as Annotation to PDF Document
Include the bwip-js library in index.html. This library is used to generate barcodes in various formats, such as QR Code, PDF417, and DataMatrix.
After retrieving the barcode content and type, use bwipjs to draw the generated barcode on a canvas. Then, convert the canvas to a blob and insert it as an annotation to the PDF document.
if (barcodeContent !== null) { try { bwipjs.toCanvas(tempCanvas, { bcid: barcodeType, text: barcodeContent, scale: 3, includetext: false, }); tempCanvas.toBlob(async (blob) => { if (blob) { let currentPageId = docs[0].pages[editViewer.getCurrentPageIndex()]; let pageData = await docs[0].getPageData(currentPageId); const option = { stamp: blob, x: pageData.mediaBox.width - 110, y: 10, width: 100, height: 100, opacity: 1.0, flags: { print: false, noView: false, readOnly: false, } } if (applyToAllPages) { for (let i = 0; iStep 6: Save the PDF Document with Barcodes to Local Disk
Create a download() function and bind it to the download button in the toolbar:
editViewer.on("download", download); async function download() { try { const pdfSettings = { saveAnnotation: "flatten", }; let blob = await editViewer.currentDocument.saveToPdf(pdfSettings); saveBlob(blob, `document_${Date.now()}.pdf`); } catch (error) { console.log(error); } } function saveBlob(blob, fileName) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }When saving the PDF document, the saveAnnotation option is set to flatten, ensuring that annotations, including the barcodes, are embedded in the document.
Running the Web PDF Document Editor
Start a web server in the root directory of your project:
python -m http.serverOpen http://localhost:8000 in your web browser.
Load a PDF document.
Insert a barcode as an annotation into the PDF document.
Reading Barcodes from PDF Documents
Once the PDF document is saved to your local disk, you can verify the barcode content by reading it with the Dynamsoft Barcode Reader.
Install barcode4nodejs, a Node.js wrapper built with the Dynamsoft C Barcode Reader SDK.
npm i barcode4nodejsCreate a script file, test.js, to read barcodes from the PDF document:
var dbr = require('barcode4nodejs'); var barcodeTypes = dbr.formats.ALL; dbr.initLicense("LICENSE-KEY"); let args = process.argv; if (args.includes('-f')) { let fIndex = args.indexOf('-f'); if (args[fIndex 1]) { (async function () { try { var result = await dbr.decodeFileAsync(args[fIndex 1], barcodeTypes, ""); console.log(result); setTimeout(() => { console.log('terminated'); }, 1000); } catch (error) { console.log(error); } })(); } else { console.log('Please add a file.'); } }Note: You need to replace the LICENSE-KEY with your own.
Run the script with the path to a PDF file:
node test.js -fThe barcode content will be printed in the console.
Source Code
https://github.com/yushulx/web-twain-document-scan-management/tree/main/examples/document_annotation
Заявление о выпуске Эта статья воспроизведена по адресу: https://dev.to/yushulx/how-to-insert-barcodes-into-a-pdf-document-with-html5-and-javascript-32g9?1 Если есть какие-либо нарушения, пожалуйста, свяжитесь с Study_golang@163 .comdeleteПоследний учебник Более>
Как вы можете использовать группу по поводу данных в MySQL?pivoting Query Results с использованием группы MySQL by В реляционной базе данных, поворот данных относится к перегруппированию строк и столбц...программирование Опубликовано в 2025-06-09
Советы по поиску позиции элемента в массиве JavaПолучение позиции элемента в массивах Java в классе массивов Java, не существует прямого «Indexof», чтобы определить позицию определенного эле...программирование Опубликовано в 2025-06-09
Как извлечь случайный элемент из массива в PHP?случайный выбор из массива в php, получение случайного элемента из массива может быть выполнено с легкостью. Рассмотрим следующий массив: ] $ite...программирование Опубликовано в 2025-06-09
Причины CodeIgniter подключиться к базе данных MySQL после перехода на MySQLIневозможно подключиться к базе данных MySQL: Сообщение об ошибке устранения неисправностей При попытке переключиться с драйвера MySQL к вашему...программирование Опубликовано в 2025-06-09
Как избежать утечек памяти при наречном языке?утечка памяти в срезах Go Понимание утечек памяти в ломтиках Go может быть вызовом. Эта статья направлена на то, чтобы дать разъяснение, изу...программирование Опубликовано в 2025-06-09
Как эффективно обнаружить пустые массивы в PHP?проверка массива в PHP Пустое массив может быть определен в PHP через различные подходы. Если необходимость заключается в проверке наличия люб...программирование Опубликовано в 2025-06-09
Могут ли параметры шаблона в C ++ 20 постоянной функции зависеть от параметров функции?постоянные функции и параметры шаблона, зависящие от аргументов функций в C 17, параметр шаблона не может зависеть от аргумента, потому что он...программирование Опубликовано в 2025-06-09
Как проанализировать числа в экспоненциальной нотации с помощью Decimal.parse ()?анализирует число из экспоненциальной нотации При попытке проанализировать строку, выраженную в экспоненциальной нотации, используя Tecimal.pa...программирование Опубликовано в 2025-06-09
Как проанализировать массивы JSON в Go, используя пакет `json`?] MARSING JSON Arrays в Go с пакетом JSON задача: Как вы можете проанализировать строку json, представляющую массив в Go, используя JSON Pack...программирование Опубликовано в 2025-06-09
Методы доступа и управления переменными среды Pythonдоступа к переменным среды в Python для доступа к переменным среды в Python Использовать os.environ объект, который представляет картировани...программирование Опубликовано в 2025-06-09
Python Metaclass Principle и создание и настройку классаЧто такое Metaclass в Python? Так же, как классы создают экземпляры, MetaClasses создают классы. Они обеспечивают уровень контроля над процессом с...программирование Опубликовано в 2025-06-09
Причины и решения для сбоя обнаружения лица: ошибка -215обработка ошибок: разрешение «ошибка: (-215)! Empty () в функции DetectMultiscale" в OpenCV при попытке использовать метод DeTectMultisca...программирование Опубликовано в 2025-06-09
Метод правильного преобразования символов Latin1 в UTF8 в таблице UTF8 MySQL] преобразовать латинские символы в таблице UTF8 в UTF8 вы столкнулись с проблемой, где символы с Diacritics (например, «Jáuò iñe») были неверн...программирование Опубликовано в 2025-06-09
Пользовательский локальный формат времени и руководство по смещению часового поясаотображение даты/времени в формате локации пользователя с смещением времени При представлении дат и времени конечным пользователям нужно отобр...программирование Опубликовано в 2025-06-09
Как эффективно вставить данные в несколько таблиц MySQL в одну транзакцию?mysql вставьте в несколько таблиц , пытаясь вставить данные в несколько таблиц с одним запросом MySQL, может дать неожиданные результаты. Хотя ...программирование Опубликовано в 2025-06-09Изучайте китайский
- 1 Как сказать «гулять» по-китайски? 走路 Китайское произношение, 走路 Изучение китайского языка
- 2 Как сказать «Сесть на самолет» по-китайски? 坐飞机 Китайское произношение, 坐飞机 Изучение китайского языка
- 3 Как сказать «сесть на поезд» по-китайски? 坐火车 Китайское произношение, 坐火车 Изучение китайского языка
- 4 Как сказать «поехать на автобусе» по-китайски? 坐车 Китайское произношение, 坐车 Изучение китайского языка
- 5 Как сказать «Ездить» по-китайски? 开车 Китайское произношение, 开车 Изучение китайского языка
- 6 Как будет плавание по-китайски? 游泳 Китайское произношение, 游泳 Изучение китайского языка
- 7 Как сказать «кататься на велосипеде» по-китайски? 骑自行车 Китайское произношение, 骑自行车 Изучение китайского языка
- 8 Как поздороваться по-китайски? 你好Китайское произношение, 你好Изучение китайского языка
- 9 Как сказать спасибо по-китайски? 谢谢Китайское произношение, 谢谢Изучение китайского языка
- 10 How to say goodbye in Chinese? 再见Chinese pronunciation, 再见Chinese learning
Декодирование изображения в формате base64
Китайский Пиньинь
Кодировка Юникод
JS-обфускация, шифрование, сжатие
Инструмент шестнадцатеричного шифрования URL-адресов
Инструмент преобразования кодировки UTF-8
Онлайн-инструменты кодирования и декодирования Ascii
Инструмент шифрования MD5
Онлайн-инструмент для шифрования и дешифрования хеша/хеш-текста
Онлайн-шифрование SHAОтказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3