Compare commits

..

No commits in common. "master" and "v0.1.7" have entirely different histories.

9 changed files with 62 additions and 51 deletions

View File

@ -2,6 +2,9 @@
Dynamically generate PDFs from Jekyll pages, posts & documents. Dynamically generate PDFs from Jekyll pages, posts & documents.
[![Build Status](https://travis-ci.org/abeMedia/jekyll-pdf.svg?branch=master)](https://travis-ci.org/abeMedia/jekyll-pdf)
[![Dependency Status](https://gemnasium.com/badges/github.com/abeMedia/jekyll-pdf.svg)](https://gemnasium.com/github.com/abeMedia/jekyll-pdf)
## Usage ## Usage
Add `gem "jekyll-pdf"` to your `Gemfile` and run `bundle`, then add `jekyll-pdf` to your `_config.yml` like so: Add `gem "jekyll-pdf"` to your `Gemfile` and run `bundle`, then add `jekyll-pdf` to your `_config.yml` like so:

View File

@ -15,6 +15,7 @@ Gem::Specification.new do |spec|
spec.add_runtime_dependency "wkhtmltopdf-installer", "~> 0.12" spec.add_runtime_dependency "wkhtmltopdf-installer", "~> 0.12"
spec.add_runtime_dependency "pdfkit", "~> 0.8" spec.add_runtime_dependency "pdfkit", "~> 0.8"
spec.add_runtime_dependency "digest", "~> 0"
spec.add_runtime_dependency "jekyll", ">= 2.0", "~> 3.1" spec.add_runtime_dependency "jekyll", ">= 2.0", "~> 3.1"
spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "bundler", "~> 1.6"

View File

@ -1 +1 @@
require 'jekyll/pdf' require "jekyll/pdf"

View File

@ -1 +1 @@
Dir[File.dirname(__FILE__) + '/pdf/**/*.rb'].each { |file| require file } Dir[File.dirname(__FILE__) + '/pdf/**/*.rb'].each {|file| require file }

View File

@ -12,56 +12,55 @@ module Jekyll
@dir = File.dirname(page.url) @dir = File.dirname(page.url)
@name = File.basename(page.url, File.extname(page.url)) + '.pdf' @name = File.basename(page.url, File.extname(page.url)) + '.pdf'
@settings = site.config.key?('pdf') ? site.config['pdf'].clone : {} @settings = site.config.key?('pdf') ? site.config['pdf'].clone : {}
@partials = %w[cover header_html footer_html] @partials = ['cover','header_html','footer_html']
process(@name) self.process(@name)
@page = page
self.data = page.data.clone self.data = page.data.clone
self.content = page.content.clone
# Set layout to the PDF layout # Set layout to the PDF layout
data['layout'] = layout self.data['layout'] = layout
# Get PDF settings from the layouts # Get PDF settings from the layouts
Jekyll::Utils.deep_merge_hashes!(@settings, get_config(data)) Jekyll::Utils.deep_merge_hashes!(@settings, self.getConfig(self.data))
PDFKit.configure do |config| PDFKit.configure do |config|
config.verbose = site.config['verbose'] config.verbose = site.config['verbose']
end end
# Set pdf_url variable in the source page (for linking to the PDF version) # Set pdf_url variable in the source page (for linking to the PDF version)
page.data['pdf_url'] = url page.data['pdf_url'] = self.url
# Set html_url variable in the source page (for linking to the HTML version) # Set html_url variable in the source page (for linking to the HTML version)
data['html_url'] = page.url self.data['html_url'] = page.url
# create the partial objects # create the partial objects
@partials.each do |partial| @partials.each do |partial|
@settings[partial] = Jekyll::PDF::Partial.new(self, @settings[partial]) unless @settings[partial].nil? @settings[partial] = Jekyll::PDF::Partial.new(self, @settings[partial]) if @settings[partial] != nil
end end
end end
# Recursively merge settings from the page, layout, site config & jekyll-pdf defaults # Recursively merge settings from the page, layout, site config & jekyll-pdf defaults
def get_config(data) def getConfig(data)
settings = data['pdf'].is_a?(Hash) ? data['pdf'] : {} settings = data['pdf'].is_a?(Hash) ? data['pdf'] : {}
layout = @site.layouts[data['layout']].data.clone unless data['layout'].nil? layout = @site.layouts[data['layout']].data.clone if data['layout'] != nil
# No parent layout found - return settings hash # No parent layout found - return settings hash
return settings if layout.nil? return settings if layout == nil
# Merge settings with parent layout settings # Merge settings with parent layout settings
layout['pdf'] ||= {} layout['pdf'] ||= {}
Jekyll::Utils.deep_merge_hashes!(layout['pdf'], settings) Jekyll::Utils.deep_merge_hashes!(layout['pdf'], settings)
get_config(layout) return self.getConfig(layout)
end end
# Write the PDF file # Write the PDF file
# todo: remove pdfkit dependency # todo: remove pdfkit dependency
def write(dest_prefix, _dest_suffix = nil) def write(dest_prefix, dest_suffix = nil)
@page.render(@site.layouts, @site.site_payload) if output.nil? self.render(@site.layouts, @site.site_payload) if self.output == nil
self.output = @page.output
path = File.join(dest_prefix, CGI.unescape(url)) path = File.join(dest_prefix, CGI.unescape(self.url))
dest = File.dirname(path) dest = File.dirname(path)
# Create directory # Create directory
@ -69,31 +68,32 @@ module Jekyll
# write partials # write partials
@partials.each do |partial| @partials.each do |partial|
@settings[partial].write unless @settings[partial].nil? @settings[partial].write if @settings[partial] != nil
end end
# Debugging - create html version of PDF # Debugging - create html version of PDF
File.open("#{path}.html", 'w') { |f| f.write(output) } if @settings['debug'] File.open("#{path}.html", 'w') {|f| f.write(self.output) } if @settings["debug"]
@settings.delete('debug') @settings.delete("debug")
@settings.delete('layout')
# Build PDF file # Build PDF file
fix_relative_paths fix_relative_paths
kit = PDFKit.new(output, @settings) kit = PDFKit.new(self.output, @settings)
file = kit.to_file(path) file = kit.to_file(path)
end end
def layout def layout()
# Set page layout to the PDF layout # Set page layout to the PDF layout
layout = data['pdf_layout'] || @settings['layout'] layout = self.data['pdf_layout'] || @settings['layout']
# Check if a PDF version exists for the current layout (e.g. layout_pdf) # Check if a PDF version exists for the current layout (e.g. layout_pdf)
if layout.nil? && !data['layout'].nil? && File.exist?('_layouts/' + data['layout'] + '_pdf.html') if layout == nil && self.data['layout'] != nil && File.exist?("_layouts/" + self.data['layout'] + "_pdf.html")
layout = data['layout'] + '_pdf' layout = self.data['layout'] + "_pdf"
end end
layout || 'pdf' layout || 'pdf'
end end
end end
end end
end end

View File

@ -5,10 +5,14 @@ module Jekyll
priority :lowest priority :lowest
def generate(site) def generate(site)
[site.pages.clone, site.documents].flatten.each do |item| # Loop through pages & documents and build PDFs
site.pages << Document.new(site, site.source, item) if item.data['pdf'] [site.pages.clone, site.documents].each do |items|
items.each do |item|
site.pages << Document.new(site, site.source, item) if item.data['pdf']
end
end end
end end
end end
end end
end end

View File

@ -2,7 +2,7 @@ module Jekyll
module PDF module PDF
module Helper module Helper
def fix_relative_paths def fix_relative_paths
output.gsub!(/(href|src)=(['"])\/([^\/"']([^\"']*|[^"']*))?['"]/, "\\1=\\2file://#{site.dest}/\\3\\2") unless output.nil? output.gsub!(/(href|src)=(['"])\/([^\/"']([^\"']*|[^"']*))?['"]/, "\\1=\\2file://#{site.dest}/\\3\\2") if output != nil
end end
end end
end end

View File

@ -1,9 +1,9 @@
# Delete temp files # Delete temp files
Jekyll::Hooks.register :site, :post_write do |jekyll, _payload| Jekyll::Hooks.register :site, :post_write do |jekyll, payload|
if jekyll.data[:jekyll_pdf_partials] if jekyll.data[:jekyll_pdf_partials]
jekyll.data[:jekyll_pdf_partials].each do |partial| jekyll.data[:jekyll_pdf_partials].each do |partial|
File.delete(partial) if File.exist?(partial) File.delete(partial) if File.exist?(partial)
end end
jekyll.data.delete(:jekyll_pdf_partials) jekyll.data.delete(:jekyll_pdf_partials)
end end
end end

View File

@ -15,7 +15,7 @@ module Jekyll
attr_writer :output attr_writer :output
def_delegators :@doc, :site, :name, :ext, :relative_path, :extname, def_delegators :@doc, :site, :name, :ext, :relative_path, :extname,
:render_with_liquid?, :collection, :related_posts :render_with_liquid?, :collection, :related_posts
# Initialize this Partial instance. # Initialize this Partial instance.
# #
@ -33,18 +33,19 @@ module Jekyll
# Returns Hash of doc data # Returns Hash of doc data
def data def data
@data ||= doc.data.dup @data ||= doc.data.dup
@data.delete('layout') @data.delete("layout")
@data @data
end end
def trigger_hooks(*); end def trigger_hooks(*)
end
def path def path
File.join(doc.path, partial) File.join(doc.path, partial)
end end
def id def id
File.basename(path, File.extname(path)) + '-' + Digest::MD5.hexdigest(to_s) + File.extname(path) File.basename(path, File.extname(path)) + "-" + Digest::MD5.hexdigest(to_s) + File.extname(path)
end end
# Returns the cache directory # Returns the cache directory
@ -65,7 +66,7 @@ module Jekyll
# Returns the shorthand String identifier of this doc. # Returns the shorthand String identifier of this doc.
def inspect def inspect
"<Partial: #{id}>" "<Partial: #{self.id}>"
end end
def output def output
@ -78,13 +79,13 @@ module Jekyll
unless File.exist?(tempfile) unless File.exist?(tempfile)
FileUtils.mkdir_p(File.dirname(tempfile)) unless File.exist?(File.dirname(tempfile)) FileUtils.mkdir_p(File.dirname(tempfile)) unless File.exist?(File.dirname(tempfile))
fix_relative_paths fix_relative_paths
File.open(tempfile, 'w') { |f| f.write(to_s) } File.open(tempfile, 'w') {|f| f.write(to_s) }
end end
@output = tempfile @output = tempfile
# store path for cleanup # store path for cleanup
site.data[:jekyll_pdf_partials] ||= [] site.data[:jekyll_pdf_partials] ||= []
site.data[:jekyll_pdf_partials] << to_s site.data[:jekyll_pdf_partials] << "#{self}"
end end
def place_in_layout? def place_in_layout?
@ -94,12 +95,12 @@ module Jekyll
protected protected
def cache_dir def cache_dir
return site.config['pdf']['cache'] if !site.config['pdf'].nil? && site.config['pdf'].key?('cache') return site.config["pdf"]["cache"] if site.config["pdf"] != nil && site.config["pdf"].has_key?('cache')
# Use jekyll-assets cache directory if it exists # Use jekyll-assets cache directory if it exists
cache_dir = site.config['assets']['cache'] || '.asset-cache' unless site.config['assets'].nil? cache_dir = site.config["assets"]["cache"] || '.asset-cache' if site.config["assets"] != nil
File.join(cache_dir || Dir.tmpdir, 'pdf') File.join(cache_dir || Dir.tmpdir(), 'pdf')
end end
# Internal: Generate partial html # Internal: Generate partial html
@ -108,22 +109,23 @@ module Jekyll
# #
# Returns partial html String # Returns partial html String
def build_partial(path) def build_partial(path)
# vars to insert into partial # vars to insert into partial
vars = %w[frompage topage page webpage section subsection subsubsection] vars = ['frompage','topage','page','webpage','section','subsection','subsubsection']
doc.data['pdf'] = {} doc.data["pdf"] = {}
vars.each { |var| doc.data['pdf'][var] = "<span class='__#{var}'></span>" } vars.each { |var| doc.data["pdf"][var] = "<span class='__#{var}'></span>" }
# JavaScript to replace var placeholders with content # JavaScript to replace var placeholders with content
script = "<script>!function(){var t={},n=document.location.search.substring(1).split('&');for(var e in n){var o=n[e].split('=',2);t[o[0]]=decodeURIComponent(o[1])}var n=#{vars};for(var e in n)for(var r=document.getElementsByClassName('__'+n[e]),a=0;a<r.length;++a)r[a].textContent=t[n[e]]}();</script>\n" script = "<script>!function(){var t={},n=document.location.search.substring(1).split('&');for(var e in n){var o=n[e].split('=',2);t[o[0]]=decodeURIComponent(o[1])}var n=#{vars};for(var e in n)for(var r=document.getElementsByClassName('__'+n[e]),a=0;a<r.length;++a)r[a].textContent=t[n[e]]}();</script>\n"
# Parse & render # Parse & render
content = File.read(File.join('_includes', path)) content = File.read(File.join("_includes", path))
# Add replacer script to body # Add replacer script to body
if content =~ /<\/body>/i if content =~ /<\/body>/i
content[/(<\/body>)/i] = script + content[/(<\/body>)/i] content[/(<\/body>)/i] = script + content[/(<\/body>)/i]
else else
Jekyll.logger.warn <<-eos Jekyll.logger.warn <<-eos
Couldn't find <body> in #{path}. Make sure your partial is a properly formatted HTML document (including DOCTYPE) e.g. Couldn't find <body> in #{path}. Make sure your partial is a properly formatted HTML document (including DOCTYPE) e.g.
<!DOCTYPE html> <!DOCTYPE html>
@ -137,18 +139,19 @@ module Jekyll
</html> </html>
eos eos
# No body found - insert html into default template # No body found - insert html into default template
content = %(<!DOCTYPE html> content = %{<!DOCTYPE html>
<html> <html>
<body> <body>
#{output} #{self.output}
#{script} #{script}
</body> </body>
</html> </html>
) }
end end
content content
end end
end end
end end
end end