Skip to content

Instantly share code, notes, and snippets.

@theideasmith
Created March 8, 2015 15:35
Show Gist options
  • Save theideasmith/12141730233910343d13 to your computer and use it in GitHub Desktop.
Save theideasmith/12141730233910343d13 to your computer and use it in GitHub Desktop.
Convert any HTML or Markdown file to a pdf
#!/usr/bin/env ruby
require 'pdfkit'
require 'redcarpet'
accepted_formats = [".html",".md"]
f_name = ARGV[0] if File.exists? ARGV[0]
f_ext = File.extname(f_name)
html_str = ""
file = File.open(f_name, "a+")
case f_ext.gsub ".",""
when "html"
html_str = file.read.chomp
when "md" || "markdown"
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(render_options = {}), extensions = {})
html_str = markdown.render(file.read.chomp)
else
raise "Filetype #{f_ext} not supported. Try again with supported filetypes #{accepted_formats.each {|i| puts i}}"
end
kit = PDFKit.new(html_str.encode("UTF-8"), :page_size => 'Letter')
# Get an inline PDF
pdf = kit.to_pdf
# Save the PDF to a file
pdf_path = File.basename(f_name.gsub(f_ext,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment