Building a Document Scanning and Barcode Recognition Application with Qt Python

Pre-requisites

  • SDK
pip install dbr
pip install PyQt5
  • License

Steps to Build a Cross-platform Document Scanning and Barcode Recognition Application

1. Create Qt application with Qt widgets

  • QWebEngineView: used to load HTML and JavaScript code. It displays the document images scanned by Dynamic Web TWAIN API.
  • QPushButton: one for acquiring images, and the other for decoding barcodes.
  • QTextEdit: show the barcode results.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel

app = QApplication([])
win = QWidget()
win.setWindowTitle('Dynamic Web TWAIN and Dynamsoft Barcode Reader')
win.show()
app.exec_()
class WebView(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)

layout = QVBoxLayout()
win.setLayout(layout)

view = WebView()
bt_scan = QPushButton('Scan Barcode Documents')
bt_read = QPushButton('Read Barcode')
text_area = QTextEdit()

layout.addWidget(view)
layout.addWidget(bt_scan)
layout.addWidget(bt_read)
layout.addWidget(text_area)
def keyPressEvent(event):
if event.key() == Qt.Key.Key_Q:
win.close()
elif event.key() == Qt.Key.Key_R:
refresh_page()

win.keyPressEvent = keyPressEvent
python app.py

2. Load HTML and JavaScript code in Qt application

import os

class WebView(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)

# Load web page and resource files to QWebEngineView
file_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), "index.html"))
local_url = QUrl.fromLocalFile(file_path)
self.load(local_url)

3. Establish the communication between Python and JavaScript

function AcquireImage() {
if (DWObject) {
var OnAcquireImageSuccess, OnAcquireImageFailure;
OnAcquireImageSuccess = OnAcquireImageFailure = function () {
DWObject.CloseSource();
};

DWObject.SelectSourceByIndex(document.getElementById("source").selectedIndex); //Use method SelectSourceByIndex to avoid the 'Select Source' dialog
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan.
DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
}
}
def read_barcode():
frame = view.page()
frame.runJavaScript('AcquireImage();')

bt_scan.clicked.connect(acquire_image)
function getCurrentImage() {
if (DWObject) {
DWObject.ConvertToBase64(
[DWObject.CurrentImageIndexInBuffer],
Dynamsoft.DWT.EnumDWT_ImageType.IT_JPG,
function (result, indices, type) {
// TODO:
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
}
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});

function getCurrentImage() {
if (DWObject) {
DWObject.ConvertToBase64(
[DWObject.CurrentImageIndexInBuffer],
Dynamsoft.DWT.EnumDWT_ImageType.IT_JPG,
function (result, indices, type) {
backend.onDataReady(result.getData(0, result.getLength()))
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
}
class Backend(QObject):
@pyqtSlot(str)
def onDataReady(self, base64img):

class WebView(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)

# Load web page and resource files to QWebEngineView
file_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), "index.html"))
local_url = QUrl.fromLocalFile(file_path)
self.load(local_url)
self.backend = Backend(self)
self.channel = QWebChannel(self.page())
self.channel.registerObject('backend', self.backend)
self.page().setWebChannel(self.channel)

def read_barcode():
frame = view.page()
frame.runJavaScript('getCurrentImage();')

bt_read.clicked.connect(read_barcode)

4. Decode barcodes from scanned documents

from dbr import *
import base64

# Initialize Dynamsoft Barcode Reader
reader = BarcodeReader()
# Apply for a trial license https://www.dynamsoft.com/customer/license/trialLicense?product=dbr
reader.init_license('LICENSE-KEY')

class Backend(QObject):
@pyqtSlot(str)
def onDataReady(self, base64img):
imgdata = base64.b64decode(base64img)

try:
text_results = reader.decode_file_stream(bytearray(imgdata), '')
if text_results != None:
out = ''
for text_result in text_results:
out += "Barcode Format : "
out += text_result.barcode_format_string + '\n'
out += "Barcode Text : "
out += text_result.barcode_text + '\n'
out += "-------------------------------------------------" + '\n'

text_area.setText(out)
except BarcodeReaderError as bre:
print(bre)

Source Code

--

--

--

Manager of Dynamsoft Open Source Projects | Tech Lover

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Building an Alexa-Based GitHub Follower Counter

Graceful Shutdown of Spring Boot Applications in Kubernetes

Data Driven Design Decision (D⁴) — with 3 incredibly simple powerful tools

Daemon Set

Choosing the Right Tools to Migrate Your Website to the Cloud — Part 5 of 7

Backing up and Restoring MS SQL Databases

Avoiding cache stampede at DoorDash

Exchange Dogecoin in chatsSuch wow!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Xiao Ling

Xiao Ling

Manager of Dynamsoft Open Source Projects | Tech Lover

More from Medium

Automate Fanduel with Python

How to Build a Chatbot in Python Using NLTK

Guide to Extract Image Metadata in Python

Web Crawling and Textual Analysis using Python — Requests (Part 1)

Course Logo: Web Crawling and Textual Analysis using Python (Instructor: Zachary Wilkerson)