不一樣的操做系統,底層使用的掃描儀驅動是不一樣的。Linux上用SANE,Windows上用TWAIN,Mac上用TWAIN或者ICA。無論上層用的是什麼高級語言 (Java, Python, JavaScript等等), 一個跨平臺的文檔掃描SDK或者軟件必須支持不一樣平臺的掃描儀訪問協議。Dynamic Web TWAIN是目前惟一一個支持Windows, Linux和macOS的文檔掃描SDK。這裏分享下如何使用Node.js來快速實現一個支持多平臺的web文檔掃描應用。javascript
參考原文:JavaScript Document Scanning for Windows, Linux and macOShtml
做者:Xiao Ling前端
翻譯:yushulxjava
1. 安裝Node.js.node
2. 建立工程document-scanning。初始化:linux
npm init
3. 經過npm安裝Express和Dynamic Web TWAIN:git
npm install express -–save npm install dwt --save
4. 建立HTML前端頁面。初始Dynamic Web TWAIN化對象:github
<script type="text/javascript" src="node_modules/dwt/dist/dynamsoft.webtwain.initiate.js"></script> <script type="text/javascript" src="node_modules/dwt/dist/dynamsoft.webtwain.config.js"></script>
打開node_modules/dwt/dist/dynamsoft.webtwain.config.js修改資源路徑:web
Dynamsoft.WebTwainEnv.ResourcesPath = '<Resource Directory>';
註冊事件監聽:express
Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used var DWObject; function Dynamsoft_OnReady() { DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer' if (DWObject) { if (window.navigator.platform.indexOf("Linux") !== -1) { DWObject.ImageCaptureDriverType = 3; } var count = DWObject.SourceCount; for (var i = 0; i < count; i++) document.getElementById("source").options.add(new Option(DWObject.GetSourceNameItems(i), i)); // Get Data Source names from Data Source Manager and put them in a drop-down box } }
觸發文檔掃描:
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); } }
在Linux上須要設定驅動類型:
DWObject.ImageCaptureDriverType = 3;
5. 建立後端的server.js:
var express = require('express'); var app = express(); app.use(express.static(__dirname)); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS"); res.header("Access-Control-Allow-Headers", "X-Requested-With, content-type"); res.header("Access-Control-Allow-Credentials", true); next(); }); var server = app.listen(2016, function() { var host = server.address().address; var port = server.address().port; console.log('listening at http://%s:%s', host, port); });
6. 啓動服務:
node server.js
7. 在瀏覽器中打開網頁http://localhost:2016/helloworld.html。如下是不一樣平臺支持的瀏覽器: