How to Scan Documents in JSP

Last Updated on 2021-06-27

If you are developing a web application in JSP and want to integrate document scanner, e.g. add a scan button which on clicking will invoke the scanning process from a scanner connected to the client machine, you can use a web-based TWAIN SDK like Dynamic Web TWAIN.

Dynamic Web TWAIN is a client-side TWAIN SDK which enables you to interact with TWAIN devices (scanners, cameras etc.) in JavaScript. Using the SDK, you can embed scan to your JSP page with just a couple of lines of code.

Scan Documents in JSP

System Requirements:

  • Compatible with Internet Explorer v6 and above, both 32 and 64 bit.
  • Compatible with Chrome and Firefox on Windows with HTML5/JavaScript library and NPAPI plugin.
  • Compatible with Safari on Mac OS X.

Code Snippet:

You can basically achieve scanning in minutes with the following JS code:

<script type="text/javascript">
function AcquireImage(){
var DWObject = Dynamsoft.DWT.GetWebTwain('dwtcontrolContainer');
DWObject.IfShowUI = false;
DWObject.SelectSource();
DWObject.OpenSource();
DWObject.AcquireImage();
}
</script>

Dynamic Web TWAIN also provides HTTP upload methods which enables you to save the scanned documents to local / server disk, database, document library as images (JPEG, PDF, TIFF, PNG, BMP), base64 and byte arrays for further processing or storing.

DWObject.HTTPUploadThroughPostEx(
strHTTPServer,
DWObject.CurrentImageIndexInBuffer,
strActionPage,
uploadfilename,
strImageType
);

The JSP code on the server side:

<%@page import="java.util.*,java.io.File,java.io.FileOutputStream,org.apache.commons.fileupload.FileUpload,org.apache.commons.fileupload.FileItem,org.apache.commons.fileupload.disk.DiskFileItemFactory,org.apache.commons.fileupload.servlet.ServletFileUpload,sun.misc.BASE64Decoder"%>
<%@page contentType="application/json; charset=utf-8" %>
<%@page language="java" %>
<%
    String strJson = "{\"success\":false}";
 
    try{
 
        // get more info from: http://commons.apache.org/proper/commons-fileupload/
 
        DiskFileItemFactory factory = new DiskFileItemFactory();
 
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
 
        ServletFileUpload upload = new ServletFileUpload(factory);
 
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
 
        String fileName = null;
        String tempFileName = null;
        String contentType = null;
        FileItem fileItem = null;
 
        while (iter.hasNext()) {
            FileItem item = iter.next();
            String fieldName = item.getFieldName();
 
            if(fieldName.equals("fileName")){
                fileName = item.getString();
            }else if(fieldName.equals("RemoteFile")){
                tempFileName = item.getName();
                contentType = item.getContentType();
                fileItem = item;
            }
        }
 
        if(fileName == null || fileName.isEmpty()){
            fileName = tempFileName;
        }
        String path = application.getRealPath(request.getServletPath());
        String dir = new java.io.File(path).getParent();
        String filePath = dir + "/UploadedImages/" + fileName;
 
        File file = new File(filePath);
 
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdir();
        }
        if(!file.exists()){
            file.createNewFile();
        }
        if(!contentType.contains("text/plain")){
            fileItem.write(file);
        }else{
            String base64Str = fileItem.getString();
            byte[] b = null;
            b = (new BASE64Decoder()).decodeBuffer(base64Str);
            FileOutputStream fileOutStream = new FileOutputStream(file);
            fileOutStream.write(b);
            fileOutStream.flush();
            fileOutStream.close();
        }
 
        strJson = "{\"success\":true, \"fileName\":\"" + fileName + "\"}";
    }
    catch(Exception ex){
        strJson = "{\"success\":false, \"error\": \"" + ex.getMessage().replace("\\", "\\\\") + "\"}";
    }
 
    out.clear();
    out.write(strJson);
    out.close();
%>

Get Sample Code NOW

Eclipse project is also available here.

Let us know if you have any questions or comments on developing a JSP application to interact with scanners.

Dynamic Web TWAIN and Server-side Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe Newsletter

Subscribe to our mailing list to get the monthly update.

Subscribename@email.com