Module: WordToPdf

Defined in:
lib/word_to_pdf/install_check.rb,
lib/word_to_pdf.rb,
lib/word_to_pdf/version.rb

Overview

lib/docx_to_pdf/install_check.rb

Defined Under Namespace

Classes: InstallCheck

Constant Summary collapse

VERSION =
'0.0.3'

Class Method Summary collapse

Class Method Details

.convert(input_docx_file_path, output_pdf_file_path, values_hash = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/word_to_pdf.rb', line 7

def self.convert(input_docx_file_path, output_pdf_file_path, values_hash = {})
  # Checking if the soffice is avaliable or not
  InstallCheck.ensure_office_installed!

  temp_dir = create_temp_dir
  filled_docx = fill_template(input_docx_file_path, values_hash, temp_dir)
  pdf_path = convert_to_pdf(filled_docx, temp_dir)

  move_pdf_to_destination(pdf_path, output_pdf_file_path)

  puts "PDF generated: #{output_pdf_file_path}"
end

.convert_to_pdf(filled_docx_path, output_dir) ⇒ Object



41
42
43
44
# File 'lib/word_to_pdf.rb', line 41

def self.convert_to_pdf(filled_docx_path, output_dir)
  system("soffice --headless --convert-to pdf #{filled_docx_path} --outdir #{output_dir}")
  filled_docx_path.gsub('.docx', '.pdf')
end

.create_temp_dirObject

creating empty tmp directory



21
22
23
24
25
# File 'lib/word_to_pdf.rb', line 21

def self.create_temp_dir
  temp_dir = "/tmp/#{SecureRandom.hex(8)}"
  Dir.mkdir(temp_dir) unless File.exist?(temp_dir)
  temp_dir
end

.fill_template(input_docx_file_path, values_hash, temp_dir) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/word_to_pdf.rb', line 27

def self.fill_template(input_docx_file_path, values_hash, temp_dir)
  doc = Docx::Document.open(input_docx_file_path)

  doc.paragraphs.each do |p|
    values_hash.each do |key, value|
      p.text = p.text.gsub("{{#{key}}}", value.to_s)
    end
  end

  filled_docx = "#{temp_dir}/filled_template.docx"
  doc.save(filled_docx)
  filled_docx
end

.move_pdf_to_destination(temp_pdf_path, final_output_path) ⇒ Object



46
47
48
# File 'lib/word_to_pdf.rb', line 46

def self.move_pdf_to_destination(temp_pdf_path, final_output_path)
  File.rename(temp_pdf_path, final_output_path)
end