Sha256: a6ae0de2bb9c986cad4626229170ba4f28229c30e4621f0772f7169209d3bd73

Contents?: true

Size: 1.14 KB

Versions: 2

Compression:

Stored size: 1.14 KB

Contents

class PDFKit
  
  # A rack middleware for validating HTML via w3c validator
  class Middleware
    
    def initialize( app )
      @app = app
    end
        
    def call( env )
      status, headers, response = @app.call( env )
      
      request = Rack::Request.new( env )
      if !request.params['pdf'].blank?
        if headers['Content-Type'] =~ /text\/html|application\/xhtml\+xml/
          body = response.body
          
          # Make absolute urls
          uri = env['REQUEST_URI'].split('?').first
          uri += '/' unless uri.match(/\/$/)
          root = env['rack.url_scheme'] + "://" + env['HTTP_HOST']
          # translate relative urls
          body.gsub!(/(href|src)=['"]([^\/][^\"']*)['"]/,'\1="'+root+'/\2"')
          
          # translate absolute urls
          body.gsub!(/(href|src)=['"]\/([^\"]*|[^']*)['"]/,'\1="'+uri+'\2"')
          
          pdf = PDFKit.new(body)
          body = pdf.to_pdf
          
          headers["Content-Length"] = body.length.to_s
          headers["Content-Type"] = "application/pdf"
          response = [body]
        end
      end
      
      [status, headers, response]
    end
  
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pdfkit-0.1.1 lib/pdfkit/middleware.rb
pdfkit-0.1.0 lib/pdfkit/middleware.rb