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 =

rubocop:disable Layout/LineLength

'<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 =

rubocop:disable Layout/LineLength

'<!DOCTYPE html><html><head><style>body {font-size: 0.5cm;}</style><title>title</title></head><body>%s</body></html>'
IMG_CID_PLAIN_REGEX =
/\[cid:(.*?)\]/m
IMG_CID_HTML_REGEX =
/cid:([^"]*)/m

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.installed?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 26

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

.run(source, target, **options) ⇒ Object



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

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



55
56
57
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
# File 'lib/libis/format/tool/msg_to_pdf.rb', line 55

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)

  # Get the body of the message in HTML
  body = msg.properties.body_html

  # Embed plain body in HTML as a fallback
  body ||= HTML_WRAPPER_TEMPLATE % msg.properties.body

  # 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 =~ %r{</head>}
      # if head exists, append the style block
      body.gsub!(%r{</head>}, "#{HEADER_STYLE}</head>")
    elsif body =~ %r{<head/>}
      # empty head, replace with the style block
      body.gsub!(%r{<head/>}, "<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|
    data = get_attachment_data(attachments, ::Regexp.last_match(1))
    if data
      used_files << ::Regexp.last_match(1)
      "<img src=\"data:#{data[:mime_type]};base64,#{data[:base64]}\"/>"
    else
      '<img src=""/>'
    end
  end

  # Then process HTML img tags with CID entries
  body.gsub!(IMG_CID_HTML_REGEX) do |_match|
    data = get_attachment_data(attachments, ::Regexp.last_match(1))
    if data
      used_files << ::Regexp.last_match(1)
      "data:#{data[:mime_type]};base64,#{data[:base64]}"
    else
      ''
    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',
      # image_quality: 100,
      # viewport_size: '2480x3508',
      dpi: 300
    }.merge pdf_options

    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) }
  else
    File.open(target, 'wb') { |f| f.write(body) }
  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 = "#{format('%0*d', digits, i)}-"
    if (sub_msg = a.instance_variable_get(:@embedded_msg))
      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 e
      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
    else
      @warnings << "Attachment #{a.properties[:display_name]} cannot be extracted"
      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:,
    headers:,
    warnings: @warnings
  }
rescue Exception => e
  raise unless root_msg

  msg.close
  {
    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



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

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