Online Document Scanning with Django and Dynamic Web TWAIN

Django is a popular framework of Python for web development. In this tutorial, we will create a web application with Django and Dynamic Web TWAIN.

About Dynamic Web TWAIN

Python Development Environment

  • Python 3.7.9

      python --version
    
  • Django 3.2.7

      python -m pip install Django
      python -m django --version
    

Overall steps

The steps that integrate Django with Dynamic Web TWAIN are:

  1. Create a Django project.
  2. Create an app inside the project.
  3. Create an HTML template that loads the Dynamic Web Twain library. The library path is dynamically generated by template syntax.
  4. Configure the path of static resource files.

Create your project with Django

Open your terminal to create a project with Django using the following command (applicable for Windows, Linux, macOS):

python -m django startproject djangodwt

Once completed, you will see the newly created project folder under your working directory.

Django working directory

Then, change your directory to djangodwt and run the app using the following command:

cd djangodwt
python manage.py runserver

After the server has been successfully started, you can visit http://127.0.0.1:8000 in a web browser.

new Django project

Now, a simple Django project has been successfully created.

Integrating with Dynamic Web TWAIN

Create the App

To build your web scanner app, you should firstly create an app.

python manage.py startapp dwt

In Django, project and app are different terminologies. An app is a Web application that does something. A project is a collection of apps that serve a particular website. For more details, refer to Writing your first Django app.

Now, the project structure is as follows.

djangodwt
  - djangodwt
    - __pycache__
    - asgi.py
    - settings.py
    - urls.py
    - wsgi.py
    - __init__.py
  - dwt
    - migrations
      - __init__.py
    - admin.py
    - apps.py
    - models.py
    - tests.py
    - views.py
    - __init__.py
  - db.sqlite3
  - manage.py

Create the view for Dynamic Web TWAIN

We will use a template to create our view. Conventionally, your template files should be placed under {project_folder/templates/{app_named_folder}/}. Let’s create one named index.html.

<!DOCTYPE html>

<head>
  <title>Dynamic Web Twain</title>
  <meta charset="utf-8">
   {% load static %} 
  <!-- Import Dynamic Web Twain library. Template will compile the actual path for us. -->
   <script type="text/javascript" src="{% static 'dwt/Resources/dynamsoft.webtwain.initiate.js' %}"></script> 
   <script type="text/javascript" src="{% static 'dwt/Resources/dynamsoft.webtwain.config.js' %}"></script>  
</head>

<body>
  <div id="app">
    <div id="dwtcontrolContainer"></div>
    <button onclick="scan()">Scan</button>
  </div>
  <script type="text/javascript">
    Dynamsoft.DWT.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady);
    Dynamsoft.DWT.ResourcesPath = 'static/dwt/Resources';
    Dynamsoft.DWT.ProductKey = 'LICENSE-KEY';
    var dwtObjct;

    function Dynamsoft_OnReady() {
      dwtObjct = Dynamsoft.DWT.GetWebTwain('dwtcontrolContainer');
    }
    function scan() {
      if (dwtObjct) {
        dwtObjct.OpenSource();
        dwtObjct.IfDisableSourceAfterAcquire = true;
        dwtObjct.AcquireImage(() => {dwtObjct.CloseSource();}, () => {dwtObjct.CloseSource();});
      }
    }
  </script>
</body>

Notice that you need a valid license key and update Dynamsoft.DWT.ProductKey = 'LICENSE-KEY' to make scanner API work. The ResourcesPath is the path to the dynamsoft.webtwain.initiate.js and dynamsoft.webtwain.config.js files. We will discuss this later.

Then we open the file dwt/views.py and put the following Python code in it:

from django.http import HttpResponse, request
from django import template
from django.shortcuts import render
import os

def index(request):
  return render(request, 'dwt/index.html')

In the app folder ({project_folder}/dwt in this case), we create another file called urls.py and include the following code.

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index')
]

Next, we go to the project’s urls.py file, which is located in {project_folder}/{project_name}. We include the newly defined rules.

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
  path('admin/', admin.site.urls),
  path('', include('dwt.urls'))
]

Finally, configure the templates directory in settings.py. We specify the template DIR as follows.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # this field
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Import Dynamic Web TWAIN

Now, it’s time to import Dynamic Web TWAIN resource files to this project.

Steps:

  1. Create a static folder under the project root.
  2. Create a dwt folder under static folder.
  3. Copy and paste Dynamic Web TWAIN SDK version/Resources folder to static/dwt/.

Afterwards, we append the following code to settings.py to make static/dwt/Resources accessible.

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

The web document scanning application developed with Dynamic Web TWAIN and Django should now work successfully.

Web document scan by Python Django

Web document management by Python Django

How to Upload Documents to Django Database

Django provides a built-in django.db.models.Model class to store data in the database. The Model class is the base class for all models in Django.

Let’s define a model class to store scanned documents in dwt/models.py:

from django.db import models

class Image(models.Model):
    name = models.CharField(max_length=30)
    data = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.name

To use the model, we need to add the name of the module that contains models.py in djangodwt/settings.py:

INSTALLED_APPS = [
    #...
    'dwt',
]

Now, we can use the following code to store scanned documents in dwt/views.py:

from .models import Image

def upload(request):
    if request.method == 'POST':
        image = Image()
        image.name = request.FILES['RemoteFile'].name
        image.data = request.FILES['RemoteFile']
        image.save()
        return HttpResponse("Successful")

    return HttpResponse("Failed")

To verify whether the database operation is successful, you can open the db.sqlite3 file in a DB browser and check its status change after uploading a document image.

Django database for storing scanned documents

Source Code

https://github.com/dynamsoft-dwt/Scan-Documents-with-Python

References

Search Blog Posts