File: js_emulation.rb

package info (click to toggle)
origami-pdf 2.1.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,484 kB
  • sloc: ruby: 17,883; makefile: 8
file content (54 lines) | stat: -rwxr-xr-x 1,296 bytes parent folder | download | duplicates (4)
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
#!/usr/bin/env ruby

begin
    require 'origami'
rescue LoadError
    $: << File.join(__dir__, "/../../lib")
    require 'origami'
end
include Origami

#
# Emulating JavaScript inside a PDF object.
#

if defined?(PDF::JavaScript::Engine)

    # Creating a new file
    pdf = PDF.new

    # Embedding the file into the PDF.
    pdf.attach_file(DATA,
        name: "README.txt",
        filter: :ASCIIHexDecode
    )

    # Example of JS payload
    pdf.onDocumentOpen Action::JavaScript <<-JS
        if ( app.viewerVersion == 8 )
          eval("this.exportDataObject({cName:'README.txt', nLaunch:2});");
        this.closeDoc();
    JS

    # Tweaking the engine options
    pdf.js_engine.options[:log_method_calls] = true
    pdf.js_engine.options[:viewerVersion] = 10

    # Hooking eval()
    pdf.js_engine.hook 'eval' do |eval, expr|
        puts "Hook: eval(#{expr.inspect})"
        eval.call(expr) # calling the real eval method
    end

    # Example of inline JS evaluation
    pdf.eval_js 'console.println(util.stringFromStream(this.getDataObjectContents("README.txt")))'

    # Executes the string as a JS script
    pdf.Catalog.OpenAction[:JS].eval_js

else
    abort "JavaScript support not found. You need to install therubyracer gem."
end

__END__
** THIS IS THE EMBEDDED FILE **