Search code examples
pythontwainimage-scanner

How to Scan Multiple File in Twain


I have developing an application in Python . I have put lost of documents to the scanner . So when pressing button I want to scan all of this documents and save into program .

import twain

sm = twain.SourceManager(0)
ss = sm.OpenSource()

for i in range(3):  //for ex. 3 documents in the scanner device
   ss.RequestAcquire(0,0)
   rv = ss.XferImageNatively()
   if rv:
       (handle, count) = rv
       twain.DIBToBMFile(handle, '{i}.bmp'.format(i))

When pressing button all of documents scanning but can not save into program . I have got an error twain.excTWCC_SEQERROR . So how can I solve this ?


Solution

  • After sending a request, you have to wait until the image is ready. Therefore, you need to set an event callback according to the TWAIN module document:

    SourceManager.SetCallback(pfnCallback)
    This method is used to set the callback handler. The callback handler is invoked when the TWAIN source signals our application. It can signal our application to indicate that there is data ready for us or that it wants to shutdown.
    The expected events are:
    MSG_XFERREADY (0x101) - the data source has data ready
    MSG_CLOSEDSREQ (0x0102) - Request for Application. to close DS
    MSG_CLOSEDSOK (0x0103) - Tell the Application. to save the state.
    MSG_DEVICEEVENT (0X0104) - Event specific to Source
    

    A possible code change:

    import twain
    
    sm = twain.SourceManager(0)
    sm.SetCallback(onTwainEvent)
    ss = sm.OpenSource()
    index = 0
    
    for i in range(3):  //for ex. 3 documents in the scanner device
       ss.RequestAcquire(0,0)
    
    def onTwainEvent(event):
        if event == twain.MSG_XFERREADY:
            saveImage()
    
    def saveImage():
        rv = ss.XferImageNatively()
        if rv:
            (handle, count) = rv
            twain.DIBToBMFile(handle, '{index}.bmp'.format(index))
            index += 1
    

    You can also refer to the pytwain code.