Skip to content

Instantly share code, notes, and snippets.

@stevenbell
Created March 23, 2017 22:24
Show Gist options
  • Save stevenbell/74bdd71d517b8216fd17971d93c4b98d to your computer and use it in GitHub Desktop.
Save stevenbell/74bdd71d517b8216fd17971d93c4b98d to your computer and use it in GitHub Desktop.
Make PDF slides from Inkscape document with layers
#!/usr/bin/env ruby
# Steven Bell <[email protected]>, based on https://gist.github.com/emk/961877
require 'rubygems'
require 'nokogiri'
require 'fileutils'
include FileUtils
# Delete all temporary PDF files
def delete_temporary_files
rm_f 'temp.svg'
Dir['slide-*.pdf'].each {|p| rm p }
end
# Script requires an input svg file
unless ARGV.length == 1
puts "Incorrect number of arguments"
puts "Usage: mkpdfs.rb SVGFILE\n"
exit
end
# Clean up any files left over from our last run.
delete_temporary_files
# Read in our presentation SVG.
doc_path = ARGV[0]
out_path = doc_path.split(".")[0] + ".pdf"
doc = open(doc_path) {|f| Nokogiri::XML(f) }
# Iterate over all the layers in our presentation.
slide_ids = []
doc.xpath('/svg:svg/svg:g[@inkscape:groupmode="layer"]').each do |layer|
# Collect the IDs of our slides.
slide_ids << layer['id']
# Hide layers labelled "hidden" (which contain our tools) and show
# all other layers.
if layer['label'] =~ /^hidden: /
layer['style'] = 'display:none'
else
layer['style'] = 'display:inline'
end
end
#slide_ids.reverse!
# Write out the modified SVG file.
File.open('temp.svg', 'w') {|f| f.write(doc.to_xml) }
# Generate a PDF for each slide.
slide_ids.each_with_index do |slide_id, i|
pdf_name = sprintf("slide-%03d.pdf", i)
puts "Exporting #{pdf_name}"
system("inkscape", "--export-pdf=#{pdf_name}", "--export-dpi=300",
"--export-id=#{slide_id}", "--export-area-page", "temp.svg") or
raise "Unable to export page"
end
# Combine our PDF files. Try pdftk first, then fallback to pdfjoin
slides = Dir["slide-*.pdf"].sort
system(*(["pdftk"] + slides + ["cat", "output", out_path])) or
system(*(["pdfjoin"] + slides + ["--outfile", out_path])) or
raise "Unable to merge PDFs - make sure pdftk or pdfjoin is installed."
# Clean up our temporary files.
delete_temporary_files
@stevenbell
Copy link
Author

I rewrote this in Python and added some features: https://gist.github.com/stevenbell/909c79c9396f932942476e658b38d80c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment