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浏览:468
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]删除最新教程 更多>
为什么Microsoft Visual C ++无法正确实现两台模板的实例?[2明确担心Microsoft Visual C(MSVC)在正确实现两相模板实例化方面努力努力。该机制的哪些具体方面无法按预期运行?背景:说明:的初始Syntax检查在范围中受到限制。它未能检查是否存在声明名称的存在,导致名称缺乏正确的声明时会导致编译问题。为了说明这一点,请考虑以下示例:一个符合...编程 发布于2025-02-19
如何可靠地检查MySQL表中的列存在?在mySQL中确定列中的列存在,验证表中的列存在与与之相比有点困惑其他数据库系统。常用的方法:如果存在(从信息_schema.columns select * * where table_name ='prefix_topic'和column_name =&...编程 发布于2025-02-19
Java是否允许多种返回类型:仔细研究通用方法?在java中的多个返回类型:一个误解介绍,其中foo是自定义类。该方法声明似乎拥有两种返回类型:列表和E。但是,情况确实如此吗?通用方法:拆开神秘 [方法仅具有单一的返回类型。相反,它采用机制,如钻石符号“ ”。分解方法签名: :本节定义了一个通用类型参数,E。它表示该方法接受扩展FOO类的任何...编程 发布于2025-02-19
为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?网格超过身体,用100%grid-template-columns 问题:考虑以下CSS和HTML: position:fixed; grid-template-columns:40%60%; grid-gap:5px; 背景:#eee; 当位置未固定时,网格将正确显示。但是,当...编程 发布于2025-02-19
在没有密码提示的情况下,如何在Ubuntu上安装MySQL?在ubuntu 使用debconf-set-selections 在安装过程中避免密码提示mysql root用户。这需要以下步骤: sudo debconf-set-selections编程 发布于2025-02-19
如何使用组在MySQL中旋转数据?在关系数据库中使用mysql组使用mysql组来调整查询结果。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的基于列的转换。通过子句以及条件汇总函数,例如总和或情况。让我们考虑以下查询: select d.data_timestamp, sum(data_id = 1 tata...编程 发布于2025-02-19
\“(1)vs.(;;):编译器优化是否消除了性能差异?\”答案:在大多数现代编译器中,while(1)和(1)和(;;)之间没有性能差异。 说明: perl: S-> 7 8 unstack v-> 4 -e语法ok 在GCC中,两者都循环到相同的汇编代码中,如下所示:。 globl t_时 t_时: .l2: movl $ .lc0,�i ...编程 发布于2025-02-19
为什么箭头函数在IE11中引起语法错误?如何修复它们?为什么arrow functions在IE 11 中引起语法错误。 IE 11不支持箭头函数,导致语法错误。这使用传统函数语法来定义与原始箭头函数相同的逻辑。 IE 11现在将正确识别并执行代码。编程 发布于2025-02-19
如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?从python 导入编解码器 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有表情符号 emoji_pattern = re.compile(“ [”...编程 发布于2025-02-19
如何检查对象是否具有Python中的特定属性?方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError:SomeClass实...编程 发布于2025-02-19
如何在JavaScript对象中动态设置键?如何为JavaScript对象变量创建动态键,尝试为JavaScript对象创建动态键,使用此Syntax jsObj['key' i] = 'example' 1;将不起作用。正确的方法采用方括号:他们维持一个长度属性,该属性反映了数字属性(索引)和一个数字属性的数量。标准对象没有模仿这...编程 发布于2025-02-19
版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?在默认值中使用current_timestamp或mysql版本中的current_timestamp或在5.6.5 这种限制源于遗产实现的关注,这些限制需要为Current_timestamp功能提供特定的实现。消息和相关问题 current_timestamp值: 创建表`foo`( `...编程 发布于2025-02-19
如何使用PHP从XML文件中有效地检索属性值?从php 您的目标可能是检索“ varnum”属性值,其中提取数据的传统方法可能会使您留下PHP陷入困境。使用simplexmlelement :: attributes()函数提供了简单的解决方案。此函数可访问对XML元素作为关联数组的属性: - > attributes()为$ attr...编程 发布于2025-02-19
哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?在Python 射线tracing方法 matplotlib路径对象表示多边形。它检查给定点是否位于定义路径内。 This function is often faster than the ray tracing approach, as seen in the code snippet pr...编程 发布于2025-02-19学习中文
- 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