Guest User

Untitled

a guest
Oct 22nd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. class PDF
  2.  
  3. PATH = "#{Rails.root}/pdfs"
  4. TMP_PATH = "#{Rails.root}/tmp/pdfs"
  5.  
  6. DEFAULT_OPTIONS = {
  7. 'footer-center' => 'Page [page]',
  8. 'footer-left' => "Mealr.net",
  9. 'footer-right' => "Copyright #{Time.now.strftime('%Y')}",
  10. 'margin-top' => '0.75in',
  11. 'margin-bottom' => '0.5in',
  12. 'margin-right' => '0.5in',
  13. 'margin-left' => '0.5in',
  14. 'page-size' => 'Letter',
  15. 'header-spacing' => '5',
  16. 'encoding' => 'UTF-8'
  17. #'load-error-handling' => 'ignore' # @todo, upgrade wkhtmltopdf on mealr server
  18. }
  19.  
  20. EXECUTABLE = '/usr/bin/env wkhtmltopdf'
  21.  
  22. attr_accessor :options, :source, :filename, :header, :stylesheets, :xmlpath, :pdfpath, :headerpath
  23.  
  24. def initialize(id, source, filename = nil, options = {})
  25. @options = DEFAULT_OPTIONS
  26. @options.merge options
  27. @source = source
  28. @id = id
  29. @filename = filename ? filename : @id
  30.  
  31. @xmlpath = "#{TMP_PATH}/#{@id}.xml"
  32. @headerpath = "#{TMP_PATH}/#{@id}-header.xml"
  33. @pdfpath = "#{PATH}/#{@filename}.pdf"
  34.  
  35. create_pdf_dir
  36. end
  37.  
  38. def to_pdf
  39. add_stylesheets
  40. check_for_custom_header
  41. save_source_as_xml
  42. generate_pdf
  43. end
  44.  
  45. protected
  46.  
  47. def create_pdf_dir
  48. Dir.mkdir("#{PATH}") unless Dir.exists?("#{PATH}")
  49. Dir.mkdir("#{TMP_PATH}") unless Dir.exists?("#{TMP_PATH}")
  50. end
  51.  
  52. def save_source_as_xml
  53. f = File.new(@xmlpath, "w")
  54. f.write @source
  55. f.close
  56. end
  57.  
  58. def add_stylesheets
  59. if @stylesheets.is_a? Array
  60. @stylesheets.each do |stylesheet|
  61. add_stylesheet stylesheet
  62. end
  63. elsif @stylesheets.is_a? String
  64. add_stylesheet stylesheet
  65. end
  66. end
  67.  
  68. def add_stylesheet(path)
  69. @source = @source.gsub(/(<\/head>)/, "<style>#{File.read(path)}</style>" +'\1')
  70. end
  71.  
  72. def check_for_custom_header
  73. f = File.new(@headerpath, "w")
  74. f.write @header
  75. f.close
  76.  
  77. @options['header-html'] = @headerpath
  78. end
  79.  
  80. def generate_pdf
  81. options = @options.map {|k,v| "--#{k} \"#{v}\"" }
  82. command = "#{EXECUTABLE} #{options.join(' ')} --quiet #{@xmlpath} #{@pdfpath}"
  83. system(command)
  84. end
  85.  
  86. end
Add Comment
Please, Sign In to add comment