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일에 게시됨검색:955
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에서 데이터를 피벗하여 그룹을 어떻게 사용할 수 있습니까?select d.data_timestamp, sum (data_id = 1 that data_value else 0 End), 'input_1'로 0 End), sum (data_id = 2 an Els.] d.data_timestamp ...프로그램 작성 2025-06-09에 게시되었습니다
Homebrew에서 GO를 설정하면 명령 줄 실행 문제가 발생하는 이유는 무엇입니까?brew go setup vs. command line execution macOS의 패키지 관리자 인 Homebrew를 사용하여 Go를 설치했습니다. Homebrew는 설치 프로세스를 단순화하지만 명령 줄 실행과 예상 동작 사이의 잠재적 불일치를 도...프로그램 작성 2025-06-09에 게시되었습니다
MySQLI로 전환 한 후 Codeigniter가 MySQL 데이터베이스에 연결 해야하는 이유문제를 디버깅하려면 파일 끝에 다음 코드를 추가하고 출력을 검토하는 것이 좋습니다. echo ''; print_r ($ db ); echo ''; echo '데이터베이스에 연결 :'. $ db ; $ dbh = mysq...프로그램 작성 2025-06-09에 게시되었습니다
`JSON '패키지를 사용하여 이동하는 JSON 어레이를 구문 분석하는 방법은 무엇입니까?JSON 어레이를 Parsing JSON 패키지 문제 : JSON 패키지를 사용하여 어레이를 나타내는 JSON 스트링을 어떻게 구문 분석 할 수 있습니까? 예 : type JsonType struct { Array []string ...프로그램 작성 2025-06-09에 게시되었습니다
오른쪽에서 CSS 배경 이미지를 찾는 방법은 무엇입니까?/ 오른쪽에서 10px 요소를 배치하려면 / 배경 위치 : 오른쪽 10px 상단; 이 CSS 상단 코너는 오른쪽 상단의 왼쪽에서 10 pixels가되어야합니다. 요소의 상단 에지. 이 기능은 Internet Explorer 8 또는 이...프로그램 작성 2025-06-09에 게시되었습니다
입력 : "경고 : mysqli_query ()는 왜 매개 변수 1이 mysqli, 주어진 리소스"오류가 발생하고이를 수정하는 방법을 기대 하는가? 출력 : 오류를 해결하는 분석 및 수정 방법 "경고 : MySQLI_QUERY () 매개 변수는 리소스 대신 MySQLI 여야합니다."mysqli_query () mysqli_query ()는 매개 변수 1이 mysqli, 리소스가 주어진 리소스, mysqli_query () 함수를 사용하여 mysql query를 실행하려고 시도 할 때 "경고 : mysqli_query (...프로그램 작성 2025-06-09에 게시되었습니다
MySQL 오류 #1089 : 잘못된 접두사 키를 얻는 이유는 무엇입니까?오류 설명 [#1089- 잘못된 접두사 키 "는 테이블에서 열에 프리픽스 키를 만들려고 시도 할 때 나타날 수 있습니다. 접두사 키는 특정 접두사 길이의 문자열 열 길이를 색인화하도록 설계되었으며, 접두사를 더 빠르게 검색 할 수 있습니...프로그램 작성 2025-06-09에 게시되었습니다
버전 5.6.5 이전에 MySQL의 Timestamp 열을 사용하여 current_timestamp를 사용하는 데 제한 사항은 무엇입니까?5.6.5 이전에 mysql 버전의 기본적으로 또는 업데이트 클로즈가있는 타임 스탬프 열의 제한 사항 5.6.5 5.6.5 이전에 mySQL 버전에서 Timestamp Holumn에 전적으로 기본적으로 한 제한 사항이 있었는데, 이는 제한적으로 전혀 ...프로그램 작성 2025-06-09에 게시되었습니다
PHP \의 기능 재정의 제한을 극복하는 방법은 무엇입니까?return $ a * $ b; } 그러나 PHP 도구 벨트에는 숨겨진 보석이 있습니다. runkit_function_rename () runkit_function_rename ( 'this', 'that'); run...프로그램 작성 2025-06-09에 게시되었습니다
크롬에서 상자 텍스트를 선택하는 방법은 무엇입니까?초기 시도 한 가지 일반적인 접근 방식은 다음과 같습니다. 주) & lt;/옵션 & gt; & lt; 옵션> select .lt {text-align : center; } <option value=""&a...프로그램 작성 2025-06-09에 게시되었습니다
PostgreSQL의 각 고유 식별자에 대한 마지막 행을 효율적으로 검색하는 방법은 무엇입니까?postgresql : 각각의 고유 식별자에 대한 마지막 행을 추출하는 select distinct on (id) id, date, another_info from the_table order by id, date desc; id ...프로그램 작성 2025-06-09에 게시되었습니다
HTML 서식 태그HTML 서식 요소 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without...프로그램 작성 2025-06-09에 게시되었습니다
PYTZ가 처음에 예상치 못한 시간대 오프셋을 표시하는 이유는 무엇입니까?import pytz pytz.timezone ( 'Asia/Hong_kong') std> discrepancy source 역사 전반에 걸쳐 변동합니다. PYTZ가 제공하는 기본 시간대 이름 및 오프...프로그램 작성 2025-06-09에 게시되었습니다
PHP를 사용하여 Blob (이미지)을 MySQL에 올바르게 삽입하는 방법은 무엇입니까?문제 $ sql = "삽입 ImagesTore (imageId, image) 값 ( '$ this- & gt; image_id', 'file_get_contents ($ tmp_image)'; 결과적으로 실제 이...프로그램 작성 2025-06-09에 게시되었습니다
Object-Fit : IE 및 Edge에서 표지가 실패, 수정 방법?이 문제를 해결하기 위해 문제를 해결하는 영리한 CSS 솔루션을 사용합니다. -50%); 높이 : 100%; 너비 : 자동; // 수직 블록의 경우 높이 : 자동; 너비 : 100%; // 수평 블록의 경우 이 조합은 절대 포지셔닝을 사용하여 중앙에서 ...프로그램 작성 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