Example how to embed binary file in HL7 message

Approximately once a week someone asks how to embed PDF file in HL7 message. Below is simplistic example.

This example will add number of binary files to OBX-5, each file as next repetition of OBX-5.

Since HL7 Standard doesn’t allow to embed binary files, content of each file has to be encoded.

This example is using base64 encoding but it can be Hex encoding too. Find more about chaining Filters here. Please note that by chaining Filters we can actually encrypt the content (AES) or compress (GZip, BZip2), as well.

This example is using PDF files as sample binary files, but please note that it can be any binary file or any ASCII file, e.g. image files in any format, DICOM files, PDF, Word, RTF, text, etc…, or even combination of numerous files of different kinds.

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

   for k,v in pairs(files) do     
      local pdf = showMeDecryption(Out.OBX[5][k]:nodeValue())

   return Out  

function readBinary()
   INPUT_DIR = 'c:\\temp\\pdf'
   FILE_PATTERN = '*.pdf' 

   -- 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')
   for k, v in pairs (List:split('\n')) do       
      local f=io.open(fPath..''..v,'rb') 

      if (f) then  
         local s=f:read("*all")  
   return files

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

function writeBinary(k,binData)
   OUTPUT_DIR = 'c:\\temp\\pdf\\Out'
   FILE_PATTERN = 'out'..tostring(k)..'.pdf' 

   local fn=fPath..FILE_PATTERN  
   local f = io.open(fn, "wb")

In this project we use pdfvmd.vmd file and sample_message.txt

Please note that this example shows also decryption of just encrypted content. This part is not functionally necessary, it is only attempt to demonstrate how to decrypt this content in Translator script.

P.S. Should we have intention to embed binary file in HL7 ver. 3.x message, process would be same, only whole example would be using XML content instead of HL7 ver. 2.x message.

For most impatient, complete project file PDF_example.zip is attached.

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.