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
تم النشر بتاريخ 2024-11-19تصفح:344
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 إذا كان هناك أي انتهاك، من فضلك اتصل بـ [email protected]أحدث البرنامج التعليمي أكثر>
هل يمكنني ترحيل التشفير الخاص بي من Mcrypt إلى OpenSSL ، وفك تشفير البيانات المشفرة Mcrypt باستخدام OpenSSL؟ترقية مكتبة التشفير الخاصة بي من mcrypt إلى openssl هل يمكنني ترقية مكتبة التشفير الخاصة بي من mcrypt إلى openssl؟ في OpenSSL ، هل من الممكن ف...برمجة نشر في 2025-06-10
الإدخال: لماذا "تحذير: mysqli_query () يتوقع أن تكون المعلمة 1 mysqli ، مورد معطى" يحدث خطأ وكيفية إصلاحه؟ الإخراج: يجب أن تكون معلمة التحليل والتثبيت لحل الخطأ "تحذير: mysqli_query () mysqli بدلاً من المورد"mysqli ، المورد المعطى "يمكن أن يحدث خطأ. يشير هذا الخطأ إلى عدم تطابق بين نوع المعلمة الأولى ونوع المورد المتوقع. لا يمكن تبديل هاتين الامتد...برمجة نشر في 2025-06-10
كيفية دمج أعمدة السنة والربع في عمود دوري واحد في الباندا؟concatenating أعمدة لعمود فترة جديدة Quarter 2001q3 الحل: df ["" Quarter "] لاحظ أنه في Python 3 ، من الضروري تحويل ...برمجة نشر في 2025-06-10
لماذا تتطلب تعبيرات Lambda متغيرات "نهائية" أو "نهائية صالحة" في جافا؟النهائي. في قصاصة الكود المقدمة: // الرمز المفقود cal.getcomponents (). getComponents ("VTimeZone"). // الرمز المفقود ...برمجة نشر في 2025-06-10
كيفية تحويل عمود DataFrame Pandas إلى تنسيق DateTime وتصفية حسب التاريخ؟تحويل عمود DataFrame pandas إلى تنسيق DateTime عند العمل مع البيانات الزمنية ، قد تظهر الطوابع الزمنية في البداية كسلاسل ولكن يجب تحويلها إلى تنس...برمجة نشر في 2025-06-10
كيفية إضافة قاعدة بيانات MySQL إلى مربع الحوار DataSource في Visual Studio 2012؟إضافة قاعدة بيانات mysql إلى مربع حوار dataSource في Visual Studio 2012 تتناول هذه المقالة هذه المشكلة وتوفر حلًا. على الرغم من تثبيت موصل MyS...برمجة نشر في 2025-06-10
كيف تسترجع أحدث مكتبة jQuery من Google APIs؟لاسترداد أحدث إصدار ، كان هناك سابقًا بديلًا لاستخدام رقم إصدار معين ، والذي كان لاستخدام بناء الجملة التالي: /latest/jquery.js Budaps &&. للحصول...برمجة نشر في 2025-06-10
كيف يرسل Android بيانات POST إلى PHP Server؟هذا سيناريو شائع عند التعامل مع الاتصالات من جانب الخادم. كيفية إرسال بيانات البريد لإرسال بيانات البريد في Android ، هناك عدة أساليب: Apach...برمجة نشر في 2025-06-10
كيف يمكنني تحديد كل النصوص برمجيًا داخل Div على الماوس؟تحديد نص div برمجيًا على الماوس انقر فوق سؤال إعطاء عنصر div بمحتوى نص ، كيف يمكن للمستخدم تحديد النص بالكامل داخل DIV بنقرة الماوس المفرد؟ يت...برمجة نشر في 2025-06-10
لماذا توجد خطوط في خلفية التدرج الخطية ، وكيف يمكنني إصلاحها؟لحفر خطوط الخلفية من التدرج الخطي عند توظيف خاصية الدرجات الخطية لخلفية ، قد تواجه خطوطًا ملحوظة عندما يتم ضبط الاتجاه على الأعلى أو الأسفل. ي...برمجة نشر في 2025-06-10
لماذا أحصل على خطأ \ "class \ 'ziparchive \' لم يتم العثور عليه \" بعد تثبيت Archive_zip على خادم Linux الخاص بي؟class 'ziparchive' لم يتم العثور على خطأ أثناء تثبيت Archive_zip على خادم Linux خطأ فادح: مشكلة ، اتبع الخطوات هذه: 1. قم بتثبيت امتدا...برمجة نشر في 2025-06-10
نصائح لالتقاط الصور العائمة على الجانب الأيمن من القاع واللف حول النصيمكن أن يخلق ذلك تأثيرًا مرئيًا جذابًا مع عرض الصورة بشكل فعال. ضمن هذه الحاوية ، أضف محتوى النص وعنصر IMG للصورة. يمكن أن يبدو رمز HTML مثل هذا: ...برمجة نشر في 2025-06-10
طريقة فعالة Python لإزالة علامات HTML من النصيمكن تحقيق ذلك من خلال تجريد علامات HTML بشكل فعال ، مما يتركك مع النص العادي المطلوب. تحقيق استخراج النص فقط مع MLSTRIPPER PYTHON يأخذ Mlstri...برمجة نشر في 2025-06-10
كيف تقوم خريطة Java و Simpleentry بتبسيط إدارة الزوجين الرئيسيين؟مجموعة شاملة لأزواج القيمة: تقديم خريطة java. ومع ذلك ، بالنسبة للسيناريوهات التي يكون فيها الحفاظ على ترتيب العناصر أمرًا بالغ الأهمية والتفرد ل...برمجة نشر في 2025-06-10
كيفية الحد من نطاق التمرير لعنصر داخل عنصر الوالد الحجم ديناميكي؟يتضمن أحد هذه السيناريو الحد من نطاق التمرير لعنصر داخل عنصر الوالدين ديناميكيًا. المشكلة: ومع ذلك ، يمتد تمرير الخريطة إلى أجل غير مسمى ، ويتج...برمجة نشر في 2025-06-10دراسة اللغة الصينية
- 1 كيف تقول "المشي" باللغة الصينية؟ 走路 نطق الصينية، 走路 تعلم اللغة الصينية
- 2 كيف تقول "استقل طائرة" بالصينية؟ 坐飞机 نطق الصينية، 坐飞机 تعلم اللغة الصينية
- 3 كيف تقول "استقل القطار" بالصينية؟ 坐火车 نطق الصينية، 坐火车 تعلم اللغة الصينية
- 4 كيف تقول "استقل الحافلة" باللغة الصينية؟ 坐车 نطق الصينية، 坐车 تعلم اللغة الصينية
- 5 كيف أقول القيادة باللغة الصينية؟ 开车 نطق الصينية، 开车 تعلم اللغة الصينية
- 6 كيف تقول السباحة باللغة الصينية؟ 游泳 نطق الصينية، 游泳 تعلم اللغة الصينية
- 7 كيف يمكنك أن تقول ركوب الدراجة باللغة الصينية؟ 骑自行车 نطق الصينية، 骑自行车 تعلم اللغة الصينية
- 8 كيف تقول مرحبا باللغة الصينية؟ # نطق اللغة الصينية، # تعلّم اللغة الصينية
- 9 كيف تقول شكرا باللغة الصينية؟ # نطق اللغة الصينية، # تعلّم اللغة الصينية
- 10 How to say goodbye in Chinese? 再见Chinese pronunciation, 再见Chinese learning
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3