Class: Libis::Format::Tool::MsgToPdf

Inherits:
Object
  • Object
show all
Includes:
Tools::Logger
Defined in:
lib/libis/format/tool/msg_to_pdf.rb

Constant Summary collapse

HEADER_STYLE =
'<style>.header-table {margin: 0 0 20 0;padding: 0;font-family: Arial, Helvetica, sans-serif;}.header-name {padding-right: 5px;color: #9E9E9E;text-align: right;vertical-align: top;font-size: 12px;}.header-value {font-size: 12px;}#header_fields {background: white;margin: 0;border: 1px solid #DDD;border-radius: 3px;padding: 8px;width: 100%%;box-sizing: border-box;}</style><script type="text/javascript">function timer() {try {parent.postMessage(Math.max(document.body.offsetHeight, document.body.scrollHeight), \'*\');} catch (r) {}setTimeout(timer, 10);};timer();</script>'
HEADER_TABLE_TEMPLATE =
'<div class="header-table"><table id="header_fields"><tbody>%s</tbody></table></div>'
HEADER_FIELD_TEMPLATE =
'<tr><td class="header-name">%s</td><td class="header-value">%s</td></tr>'
HTML_WRAPPER_TEMPLATE =
'<!DOCTYPE html><html><head><style>body {font-size: 0.5cm;}</style><title>title</title></head><body>%s</body></html>'
IMG_CID_PLAIN_REGEX =
%r/\[cid:(.*?)\]/m
IMG_CID_HTML_REGEX =
%r/cid:([^"]*)/m

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.installed? ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 29

def self.installed?
  File.exist?(Libis::Format::Config[:wkhtmltopdf])
end

.run(source, target, options = {}) ⇒ Object



33
34
35
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 33

def self.run(source, target, options = {})
  new.run source, target, options
end

Instance Method Details

#msg_to_pdf(msg, target, target_format, pdf_options, root_msg: true) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 58

def msg_to_pdf(msg, target, target_format, pdf_options, root_msg: true)

  # Make sure the target directory exists
  outdir = File.dirname(target)
  FileUtils.mkdir_p(outdir)

# puts "Headers:"
# puts '--------'
# pp msg.headers

# puts "Recipients:"
# puts '-----------'
# pp msg.recipients

# puts "Body:"
# puts '-----'
# puts msg.properties.body
# puts '-----'
# puts msg.properties.body_rtf
# puts '-----'
# puts msg.properties.body_html

# puts "Attachments:"
# puts '------------'
# msg.attachments.each {|a| p "#{a.filename} - #{a.properties.attach_content_id}"}

# puts "Converting:"
# puts '-----------'

  # Get the body of the message in HTML
  body = msg.properties.body_html
  body ||= begin
    # Embed plain body in HTML as a fallback
    HTML_WRAPPER_TEMPLATE % msg.properties.body
  end

  # Check and fix the character encoding
  begin
    # Try to encode into UTF-8
    body.encode!('UTF-8', universal_newline: true)
  rescue Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError
    begin
    # If it fails, the text may be in Windows' Latin1 (ISO-8859-1)
    body.force_encoding('ISO-8859-1').encode!('UTF-8', universal_newline: true)
    rescue Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError => e
      # If that fails too, log a warning and replace the invalid/unknown with a ? character.
      @warnings << "#{e.class}: #{e.message}"
      body.encode!('UTF-8', universal_newline: true, invalid: :replace, undef: :replace)
    end
  end

  # Process headers
  # ---------------
  headers = {}
  hdr_html = ''

  %w"From To Cc Subject Date".each do |key|
    value = find_hdr(msg.headers, key)
    if value
      headers[key.downcase.to_sym] = value
      hdr_html += hdr_html(key, value)
    end
  end

  [:date].each do |key|
    next unless headers[key]
    headers[key] = DateTime.parse(headers[key]).to_time.localtime.iso8601
  end

  # Add header section to the HTML body
  unless hdr_html.empty?
    # Insert header block styles
    if body =~ /<\/head>/
      # if head exists, append the style block
      body.gsub!(/<\/head>/, HEADER_STYLE + '</head>')
    else
      # otherwise insert a head section before the body tag
      body.gsub!(/<body/, '<head>' + HEADER_STYLE + '</head><body')
    end
    # Add the headers html table as first element in the body section
    body.gsub!(/<body[^>]*>/) {|m| "#{m}#{HEADER_TABLE_TEMPLATE % hdr_html}"}
  end

  # Embed inline images
  # -------------------
  attachments = msg.attachments
  used_files = []

  # First process plaintext cid entries
  body.gsub!(IMG_CID_PLAIN_REGEX) do |match|
# puts "CID found: #{match}, looking for #{$1}"
    data = getAttachmentData(attachments, $1)
    if data
# puts "cid #{$1} data: #{data.inspect}"
      used_files << $1
      "<img src=\"data:#{data[:mime_type]};base64,#{data[:base64]}\"/>"
    else
  # puts "cid #{$1} not found"
      '<img src=""/>'
    end
  end
  
  # Then process HTML img tags with CID entries
  body.gsub!(IMG_CID_HTML_REGEX) do |match|
# puts "CID found: #{match}, looking for #{$1}"
    data = getAttachmentData(attachments, $1)
    if  data
# puts "cid #{$1} data: #{data.inspect}"
    used_files << $1
    "data:#{data[:mime_type]};base64,#{data[:base64]}"
    else
# puts "cid #{$1} not found"
      ''
    end
  end

  # Create PDF
  # ----------
  files = []

  if target_format == :PDF
  # PDF creation options
    pdf_options = {
      page_size: 'A4',
      margin_top: '10mm',
      margin_bottom: '10mm',
      margin_left: '10mm',
      margin_right: '10mm',
      dpi: 300,
      # image_quality: 100,
      # viewport_size: '2480x3508',
    }.merge pdf_options

# pp pdf_options
# puts "Final HTML body:"
# pp body
    subject = find_hdr(msg.headers, 'Subject')
    kit = PDFKit.new(body, title: (subject || 'message'), **pdf_options)
    pdf = kit.to_pdf
    File.open(target, 'wb') {|f| f.write(pdf)}
# puts "message #{subject} converted to PDF file '#{target}'"
  else
    File.open(target, 'wb') {|f| f.write(body)}
# puts "message #{subject} converted to HTML file '#{target}'"
  end
  files << target if File.exist?(target)

  # Save attachments
  # ----------------
  outdir = File.join(outdir, "#{File.basename(target)}.attachments")
  digits = ((attachments.count + 1)/ 10) + 1
  i = 1
  attachments.delete_if {|a| a.properties.attachment_hidden}.each do |a|
    prefix = "#{"%0*d" % [digits, i]}-"
    if sub_msg = a.instance_variable_get(:@embedded_msg)
# puts "Embedded email message ..."
      subject = a.properties[:display_name] || sub_msg.subject || ""
      file = File.join(outdir, "#{prefix}#{subject}.msg.#{target_format.to_s.downcase}")

      result = msg_to_pdf(sub_msg, file, target_format, pdf_options, root_msg: false)
      if e = result[:error]
        raise 
      end
      files += result[:files]
    elsif a.filename
      next if used_files.include?(a.filename)
      file = File.join(outdir, "#{prefix}#{a.filename}")

      FileUtils.mkdir_p(File.dirname(file))
      File.open(file, 'wb') {|f| a.save(f)}
      files << file
# puts "Attachment file '#{file}' created"
    else
      @warnings << "Attachment #{a.properties[:display_name]} cannot be saved"
      next
    end
    i += 1
  end

  if root_msg
    p = Pathname(File.dirname(files.first))
    files[1..].each do |f|
      (headers[:attachments] ||= []) << Pathname.new(f).relative_path_from(p).to_s
    end
  end
  
  {
    command: {status: 0},
    files: files,
    headers: headers,
    warnings: @warnings
  }
  
rescue Exception => e
# puts "ERROR: Exception #{e.class} raised: #{e.message}"
# e.backtrace.each {|t| puts " - #{t}"}
  raise unless root_msg
  msg.close
  return {
    command: {status: -1},
    files: [],
    headers: {},
    errors: [
      {
        error: e.message,
        error_class: e.class.name,
        error_trace: e.backtrace,
      }
    ],
    warnings: @warnings
  }
end

#run(source, target, options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 37

def run(source, target, options = {})
  # Preliminary checks
  # ------------------

  @warnings = []

  # Check if source file exists
  raise "File #{source} does not exist" unless File.exist?(source)

  # Retrieving the message
  # ----------------------

  # Open the message
  msg = Mapi::Msg.open(source)

  target_format = options.delete(:to_html) ? :HTML : :PDF
  result = msg_to_pdf(msg, target, target_format, options)
  msg.close
  result
end