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
如何使用 HTMLnd JavaScript 將條碼插入 PDF 文檔
發佈於2024-11-19瀏覽:567
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 .com刪除最新教學 更多>
如何使用組在MySQL中旋轉數據?在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。 Let's consider the following ...程式設計 發佈於2025-06-09
查找當前執行JavaScript的腳本元素方法如何引用當前執行腳本的腳本元素在某些方案中理解問題在某些方案中,開發人員可能需要將其他腳本動態加載其他腳本。但是,如果Head Element尚未完全渲染,則使用document.getElementsbytagname('head')[0] .appendChild(v)的常規方...程式設計 發佈於2025-06-09
Java數組中元素位置查找技巧在Java數組中檢索元素的位置 利用Java的反射API將數組轉換為列表中,允許您使用indexof方法。 (primitives)(鏈接到Mishax的解決方案) 用於排序陣列的數組此方法此方法返回元素的索引,如果發現了元素的索引,或一個負值,指示應放置元素的插入點。程式設計 發佈於2025-06-09
如何從PHP中的數組中提取隨機元素?從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。程式設計 發佈於2025-06-09
切換到MySQLi後CodeIgniter連接MySQL數據庫失敗原因無法連接到mySQL數據庫:故障排除錯誤消息要調試問題,建議將以下代碼添加到文件的末尾.//config/database.php並查看輸出: ... ... 迴聲'... echo '<pre>'; print_r($db['default']); echo '</pr...程式設計 發佈於2025-06-09
如何避免Go語言切片時的內存洩漏?,a [j:] ...雖然通常有效,但如果使用指針,可能會導致內存洩漏。這是因為原始的備份陣列保持完整,這意味著新切片外部指針引用的任何對象仍然可能佔據內存。 copy(a [i:] 對於k,n:= len(a)-j i,len(a); k程式設計 發佈於2025-06-09
在PHP中如何高效檢測空數組?在PHP 中檢查一個空數組可以通過各種方法在PHP中確定一個空數組。如果需要驗證任何數組元素的存在,則PHP的鬆散鍵入允許對數組本身進行直接評估:一種更嚴格的方法涉及使用count()函數: if(count(count($ playerList)=== 0){ //列表為空。 } 對...程式設計 發佈於2025-06-09
C++20 Consteval函數中模板參數能否依賴於函數參數?[ consteval函數和模板參數依賴於函數參數在C 17中,模板參數不能依賴一個函數參數,因為編譯器仍然需要對非contexexpr futcoriations contim at contexpr function進行評估。 compile time。 C 20引入恆定函數,必須在編譯時進...程式設計 發佈於2025-06-09
如何使用Depimal.parse()中的指數表示法中的數字?在嘗試使用Decimal.parse(“ 1.2345e-02”中的指數符號表示法表示的字符串時,您可能會遇到錯誤。這是因為默認解析方法無法識別指數符號。 成功解析這樣的字符串,您需要明確指定它代表浮點數。您可以使用numbersTyles.Float樣式進行此操作,如下所示:[&& && && ...程式設計 發佈於2025-06-09
如何使用“ JSON”軟件包解析JSON陣列?parsing JSON與JSON軟件包 QUALDALS:考慮以下go代碼:字符串 } func main(){ datajson:=`[“ 1”,“ 2”,“ 3”]`` arr:= jsontype {} 摘要:= = json.unmarshal([] byte(...程式設計 發佈於2025-06-09
Python環境變量的訪問與管理方法Accessing Environment Variables in PythonTo access environment variables in Python, utilize the os.environ object, which represents a mapping of envir...程式設計 發佈於2025-06-09
Python元類工作原理及類創建與定制python中的metaclasses是什麼? Metaclasses負責在Python中創建類對象。就像類創建實例一樣,元類也創建類。他們提供了對類創建過程的控制層,允許自定義類行為和屬性。 在Python中理解類作為對象的概念,類是描述用於創建新實例或對象的藍圖的對象。這意味著類本身是使用...程式設計 發佈於2025-06-09
人臉檢測失敗原因及解決方案:Error -215錯誤處理:解決“ error:( - 215)!empty()in Function openCv in Function MultSiscale中的“檢測”中的錯誤:在功能檢測中。”當Face Cascade分類器(即面部檢測至關重要的組件)未正確加載時,通常會出現此錯誤。 要解決此問題,必...程式設計 發佈於2025-06-09
在UTF8 MySQL表中正確將Latin1字符轉換為UTF8的方法在UTF8表中將latin1字符轉換為utf8 ,您遇到了一個問題,其中含義的字符(例如,“jáuòiñe”)在utf8 table tabled tablesset中被extect(例如,“致電。為了解決此問題,您正在嘗試使用“ mb_convert_encoding”和“ iconv”轉換受...程式設計 發佈於2025-06-09
input: Why Does "Warning: mysqli_query() expects parameter 1 to be mysqli, resource given" Error Occur and How to Fix It? output: 解決“Warning: mysqli_query() 參數應為 mysqli 而非 resource”錯誤的解析與修復方法mysqli_query()期望參數1是mysqli,resource給定的,嘗試使用mysql Query進行執行MySQLI_QUERY_QUERY formation,be be yessqli:sqli:sqli:sqli:sqli:sqli:sqli: mysqli,給定的資源“可能發...程式設計 發佈於2025-06-09學習中文
- 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