Sha256: ee0919e037d8ad9bc5267de7bbb87685da072bfc19e42d909a93b6732eb8a043

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

require "open3"
require "fileutils"
require_relative "../html2pdf"
module Html2Pdf
  class << self
    # Batch convert to pdf using `wkhtmltopdf` tool
    #
    # @param [Array<String>] files the input file list
    # @param [String] base_dir the base directory
    def to_pdfs(files)
      files.each_with_index do |file, index|
        puts "Convert file #{index + 1} of #{files.size} : #{file}"
        to_pdf(file)
      end
    end

    # Convert '*.xhtml' or '*.html' to pdf
    #
    # @param filename input filename
    def to_pdf(filename)
      fail "Invalid input file #{filename}" unless File.exist?(filename)
      # TODO: allow custom configuration
      command = [
        "wkhtmltopdf",
        "--margin-top 4",
        "--margin-bottom 4",
        "--margin-left 4",
        "--margin-right 4",
        '--header-center "[webpage] :: [page]/[topage]"',
        "--header-spacing 1",
        "--header-font-size 8",
        "--header-line",
        "--footer-spacing 1",
        "--footer-font-size 8",
        "--footer-line",
        "#{filename}",
        "#{filename}.pdf",
        "> /dev/null"]
      _stdin, _stderr, status = Open3.capture3(command.join(" "))
      fail "Problem processing #{filename}" unless status.success?
    end

    # Check and return if the 'wkhtmltopdf' is available
    def softwares_installed?
      AgileUtils::Helper.which("wkhtmltopdf")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
html2pdf-0.1.6 lib/html2pdf/html2pdf.rb
html2pdf-0.1.5 lib/html2pdf/html2pdf.rb