summaryrefslogtreecommitdiff
path: root/lib/page_pdf.rb
blob: e70c88724996a2e7c9b2e3dbbebd46b4b1d54d70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# coding: utf-8
require 'erb'
require 'open3'
require 'yaml'

require 'page_local'

class PdfPage < LocalPage
	def initialize(filename)
		super(filename)
	end

	def pdf_metadata
		if @metadata.nil?
			stdout, stderr, status = Open3::capture3("pdfinfo", "--", local_infile)
			unless stderr.empty?
				raise stderr
			end
			unless status.success?
				raise status
			end
			raw_metadata = stdout.split("\n").map{|l|l.split(":", 2).map{|c|c.strip}}.to_h

			# Transform the PDF property names to match our metadata names
			key_map = {
				"Title" => "title",
				"Author" => "author",
				"CreationDate" => "published",
				"ModDate" => "updated",
				# "Keywords" => "categories",
			}
			@metadata = raw_metadata.map{|k,v|[key_map[k]||k,v]}.to_h

			yamlfile = local_infile.sub(/\.pdf$/, '.yaml')
			if File::exist?(yamlfile)
				@metadata = @metadata.merge(YAML::load(File::read(yamlfile)))
			end
		end
		@metadata
	end
	def pdf_js_url
		@@pdjfs ||= Config::get.url + 'pdfjs/web/viewer.html'
	end
	def pdf_viewer_url
		@viewer_url ||= pdf_js_url + ('?file=' + URI::encode_www_form_component(pdf_js_url.route_to(local_srcurl)))
	end

	def local_intype
		return 'markdown'
	end
	def local_depends
		if @depends.nil?
			yamlfile = local_infile.sub(/\.pdf$/, '.yaml')
			metafile = File::exist?(yamlfile) ? yamlfile : File::dirname(yamlfile)
			tmplfile = "tmpl/pdf.md.erb"
			@depends = super.map{|k,v|[k,v.merge([metafile, tmplfile])]}.to_h
		end
		@depends
	end
end

ERB::new(File::read("tmpl/pdf.md.erb")).def_method(PdfPage, 'local_input()', "tmpl/pdf.md.erb")