Skip to content

Instantly share code, notes, and snippets.

@ebot
Created October 6, 2009 12:49
Show Gist options
  • Save ebot/202989 to your computer and use it in GitHub Desktop.
Save ebot/202989 to your computer and use it in GitHub Desktop.
Merge seperate pdfs into one, using iText
#!/usr/bin/env ruby -wKU
require 'rubygems'
require 'fastercsv'
require 'yaml'
begin
# Gather the encounter information
map = YAML::load( File.new( 'encounter-map.yml', 'r' ) )
encounters = {}
csv_options = {:col_sep => ';', :headers => :first_row,
:write_headers => true}
index_file = FasterCSV.open '../index.txt', csv_options
new_index = []
header = nil
index_file.each do |row|
if encounters[row["encounter_number"]].nil?
encounters[row["encounter_number"]] = Hash.new
encounters[row["encounter_number"]][:documents] = Hash.new
encounters[row["encounter_number"]][:medical_record_number] =
row["medical_record_number"]
encounters[row["encounter_number"]][:patient_name] = row["patient_name"].gsub(/ /, '-')
encounters[row["encounter_number"]][:admit_date] = row["visit_start_date"]
end
encounters[row["encounter_number"]][:documents][row["file_name"]] =
row["document_type"]
end
# Merge the documents into one PDF by encounter number
encounters.each do |k, v|
puts "#{k} => #{v[:medical_record_number]} (#{v[:documents].size})"
# Set the new file name -encounterNumber_patientName_admit-Date_memberID.pdf
# Get the admit date
admit_date = v[:admit_date][4, 6] << "-" << v[:admit_date][v[:admit_date].length-4, 4]
admit_date = admit_date.gsub(/ /, '-')
insurance = map[k.to_i]['insurance'] unless map[k.to_i] == nil # Get the insurance member id
file_name = "../documents/#{k}_#{v[:patient_name].gsub( /,/, '' )}_#{admit_date}_#{insurance}.pdf"
puts " #{file_name}"
# Get the list of files for the encounter and sort by the doc type
files = ""
v[:documents].sort { |d, t| d[1]<=>t[1] }.each do |doc|
files << ";" if files.length > 1
files << "../data/#{doc[0]}"
end
command = "java -classpath itext.jar; PdfCombine #{file_name} #{files}"
IO.popen(command) { |f| puts " #{f.gets}" }
end
rescue Exception => e
puts e.message
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment