Embed a binary file in an HL7 message

Added by iNTERFACEWARE

How to encode binary files as base 64 text, then embed them as OBX-5 segment repeats

Source Code
-- this code uses local functions (best practice) at the start of the code
-- this requires that main() is placed at the end of the code
-- as it requires to be after the local functions it calls

local function readBinary()
   INPUT_DIR = 'c:\\temp\\pdf'
   FILE_PATTERN = '*.pdf' 
   fPath=INPUT_DIR..'\\'
   
   -- if running on Win then command to use is 'dir /b'
   -- with different OS command may be different
   local files={}
   local P = io.popen('dir /b '..fPath..FILE_PATTERN)
   local List = P:read('*a')
   trace(List)
   for k, v in pairs (List:split('\n')) do       
      local f=io.open(fPath..''..v,'rb') 
      
      if (f) then  
         local s=f:read("*all")  
         files[k]=s
         io.close(f) 
      end 
   end  
   return files
end

local function showMeDecryption(s)
   return filter.base64.dec(s)
end

function writeBinary(k,binData)
   OUTPUT_DIR = 'c:\\temp\\pdf\\Out'
   FILE_PATTERN = 'out'..tostring(k)..'.pdf' 
   fPath=OUTPUT_DIR..'\\'
   
   local fn=fPath..FILE_PATTERN  
   local f = io.open(fn, "wb")
   f:write(binData)
   f:close()   
end

function main(Data)
   
   local Msg=hl7.parse{vmd='pdfvmd.vmd', data=Data}
   local Out=hl7.message{vmd='pdfvmd.vmd', name='PDFreport'}
   local files=readBinary()
   
   for k,v in pairs(files) do
      Out.OBX[5][k]=filter.base64.enc(files[k])
   end
   
   for k,v in pairs(files) do     
      local pdf = showMeDecryption(Out.OBX[5][k]:nodeValue())
      writeBinary(k,pdf)  
   end
   
   return Out  
end
Description
How to encode binary files as base 64 text, then embed them as OBX-5 segment repeats