Skip to content

Instantly share code, notes, and snippets.

@duhast
Created January 6, 2017 15:50
Show Gist options
  • Select an option

  • Save duhast/3b9dfe0b8ed608855b9b0b52881de33c to your computer and use it in GitHub Desktop.

Select an option

Save duhast/3b9dfe0b8ed608855b9b0b52881de33c to your computer and use it in GitHub Desktop.
ImageMagick helper to import custom fonts from Ruby
# ImageMagick helper to import custom fonts from Ruby instead of imagick_type_gen python script
# Designed for OSX/Heroku
# Usage:
# desc 'Init custom fonts'
# task fonts: :environment do
# ImagemagickFontTool.export_type_xml(nil, '/app') # For Heroku
# if Rails.env.development?
# home_type_config = File.expand_path '~/.magick/myapp-type.xml' # Need to register this manually in ~/.magick/type.xml
# ImagemagickFontTool.export_type_xml home_type_config
# end
# end
class ImagemagickFontTool
FONT_EXTENSIONS = %w(ttf otf)
def self.export_type_xml(target_xml_path = nil, override_font_path = nil)
fonts_folder_path = Rails.root.join('db/fonts')
font_files = Dir["#{fonts_folder_path}/**/*"].select do |path|
File.file?(path) && FONT_EXTENSIONS.include?(File.extname(path)[1..-1])
end
builder = Nokogiri::XML::Builder.new do |xml|
xml.typemap do
font_files.each do |ttf_file|
ttf = TTFunk::File.open(ttf_file)
format = File.extname(ttf_file)[1..-1]
attrs = {
format: format,
name: ttf.name.postscript_name,
glyphs: ttf_file
}
if format == 'ttf'
family = ttf.name.font_family[0..1]
name = ttf.name.font_name[0..1]
subfamily = ttf.name.font_subfamily[0..1]
attrs[:name] = name.first
attrs[:family] = family.first
# full_name = name.last || name.first
# attrs[:name] = name.first
# attrs[:fullname] = full_name unless full_name == attrs[:name]
# attrs[:family] = family.first unless family.first == attrs[:name]
# style = subfamily.first.downcase
# attrs[:style] = style if %w(bold italic regular).any?{|s| style.include?(s) }
end
if override_font_path
attrs[:glyphs] = File.join(override_font_path, File.basename(ttf_file))
end
xml.type attrs #.map{|k,v| [k, v.to_s] }.to_h
end
end
end
target_xml_path ||= Rails.root.join('.magick', 'type.xml')
File.open(target_xml_path, 'w'){|f| f.write builder.to_xml}
target_xml_path
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment