### Install Puppeteer Source: https://github.com/studiosity/grover/blob/main/README.md Install the Google Puppeteer Node.js package, a dependency for Grover. ```bash npm install puppeteer ``` -------------------------------- ### Basic PDF Conversion with Grover Source: https://context7.com/studiosity/grover/llms.txt Demonstrates how to convert a URL or inline HTML string into a PDF document using the Grover gem. Includes examples of saving the PDF to a file or directly to a specified path, with options for formatting like 'A4' or 'Letter'. ```ruby require 'grover' # Convert a URL to PDF grover = Grover.new('https://google.com', format: 'A4') pdf_data = grover.to_pdf # Save to file File.open('output.pdf', 'wb') { |f| f << pdf_data } # Or write directly to path grover.to_pdf('/path/to/output.pdf') # Convert inline HTML to PDF html = '

Hello World

Generated with Grover

' grover = Grover.new(html, format: 'Letter') pdf_data = grover.to_pdf ``` -------------------------------- ### Install Grover Gem and Puppeteer Source: https://context7.com/studiosity/grover/llms.txt Instructions for installing the Grover Ruby gem and its dependency, Puppeteer, via npm. This is a prerequisite for using Grover's conversion functionalities. ```ruby # Gemfile gem 'grover' ``` ```bash npm install puppeteer ``` -------------------------------- ### Grover Middleware Setup Source: https://github.com/studiosity/grover/blob/main/README.md Integrate Grover's middleware into your Rack or Rails application to generate PDF, PNG, or JPEG views of pages by appending file extensions to URLs. ```APIDOC ## Middleware Grover comes with a middleware that allows users to get a PDF, PNG or JPEG view of any page on your site by appending .pdf, .png or .jpeg/.jpg to the URL. ### Middleware Setup **Non-Rails Rack apps** ```ruby # in config.ru require 'grover' use Grover::Middleware ``` **Rails apps** ```ruby # in application.rb require 'grover' config.middleware.use Grover::Middleware ``` N.B. by default PNG and JPEG are not modified in the middleware to prevent breaking standard behaviours. To enable them, there are configuration options for each image type as well as an option to disable the PDF middleware (on by default). If either of the image handling middleware options are enabled, the [ignore_path](#ignore_path) and/or [ignore_request](#ignore_request) should also be configured, otherwise assets are likely to be handled which would likely result in 404 responses. ### Enabling Image Middleware ```ruby # config/initializers/grover.rb Grover.configure do |config| config.use_png_middleware = true config.use_jpeg_middleware = true config.use_pdf_middleware = false end ``` ``` -------------------------------- ### Grover Middleware Setup for Rack and Rails Apps Source: https://github.com/studiosity/grover/blob/main/README.md Integrate Grover's middleware into your application to enable generating PDF, PNG, or JPEG versions of web pages by appending file extensions to URLs. This setup can be done for non-Rails Rack applications or Rails applications. ```ruby # in config.ru require 'grover' use Grover::Middleware ``` ```ruby # in application.rb require 'grover' config.middleware.use Grover::Middleware ``` -------------------------------- ### Install Grover Gem Source: https://github.com/studiosity/grover/blob/main/README.md Add the Grover gem to your application's Gemfile for installation. ```ruby gem 'grover' ``` -------------------------------- ### Connect to Remote Chromium Instance Source: https://github.com/studiosity/grover/blob/main/README.md Explains how to connect Grover to an external Chromium instance using a WebSocket endpoint and how to install the necessary lightweight dependency. ```ruby grover = Grover.new("https://mysite.com/path/to/thing", browser_ws_endpoint: "ws://localhost:3000/chrome") File.open("grover.png", "wb") { |f| f << grover.to_png } ``` ```shell npm install puppeteer-core ``` -------------------------------- ### Manage Request Cookies Source: https://github.com/studiosity/grover/blob/main/README.md Provides examples for setting static cookies and extracting cookies from an existing request to forward them to Grover. ```ruby myCookies = [ { name: 'sign_username', value: 'any@any.com', domain: 'mydomain' }, { name: '_session_id', value: '9c014df0b699d8dc08d1c472f8cc594c', domain: 'mydomain' } ] Grover.new(' ``` -------------------------------- ### Configure Basic Authentication in Grover Source: https://github.com/studiosity/grover/blob/main/README.md Demonstrates how to provide username and password credentials to Grover for authenticated page requests. ```ruby Grover.new(' ... ``` -------------------------------- ### Grover Options via Meta Tags Source: https://github.com/studiosity/grover/blob/main/README.md Illustrates how to pass Grover options, such as page ranges and margins, using meta tags within the HTML head. ```ruby Grover.new('', browser: 'firefox').to_pdf ``` -------------------------------- ### Render Rails View to PDF Source: https://github.com/studiosity/grover/blob/main/README.md Shows how to render a Rails view template to HTML using `render_to_string` and then convert it to a PDF using Grover. ```ruby html = MyController.new.render_to_string({ template: 'controller/view', layout: 'my_layout', locals: { :@instance_var => ... } }) pdf = Grover.new(html, **grover_options).to_pdf ``` -------------------------------- ### Enable File URI Rendering with Caution Source: https://github.com/studiosity/grover/blob/main/README.md Configure Grover to allow rendering HTML documents directly from the file system using `allow_file_uris`. This feature should be used with extreme caution due to potential security risks. It defaults to false. ```ruby # config/initializers/grover.rb Grover.configure do |config| config.allow_file_uris = true end ``` ```ruby # Grover.new accepts a file URI and optional parameters for Puppeteer grover = Grover.new('file:///some/local/file.html', format: 'A4') # Get an inline PDF of the local file pdf = grover.to_pdf ``` -------------------------------- ### Configure Wait Conditions for Rendering Source: https://context7.com/studiosity/grover/llms.txt Demonstrates how to control the timing of PDF generation by waiting for specific DOM elements, JavaScript conditions, or network idle states. ```ruby grover = Grover.new('https://spa-app.com', wait_for_selector: '#content-loaded', wait_for_selector_options: { visible: true, timeout: 10000 }) pdf = grover.to_pdf grover = Grover.new('https://example.com', wait_for_function: 'window.dataLoaded === true', wait_for_function_options: { timeout: 5000 }) pdf = grover.to_pdf grover = Grover.new('https://example.com', wait_for_timeout: 2000, wait_until: 'networkidle0') pdf = grover.to_pdf ``` -------------------------------- ### Global Configuration for Grover Source: https://context7.com/studiosity/grover/llms.txt Details how to configure default options, middleware settings, and runtime parameters for all Grover instances using `Grover.configure`. This includes setting PDF formats, margins, user agents, viewports, and various other Puppeteer-related options. ```ruby # config/initializers/grover.rb Grover.configure do |config| config.options = { format: 'A4', margin: { top: '5px', bottom: '10cm', left: '1cm', right: '1cm' }, user_agent: 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)', viewport: { width: 1280, height: 1024 }, prefer_css_page_size: true, emulate_media: 'screen', bypass_csp: true, media_features: [{ name: 'prefers-color-scheme', value: 'dark' }], timezone: 'Australia/Sydney', extra_http_headers: { 'Accept-Language' => 'en-US' }, cache: false, timeout: 0, launch_timeout: 3000, request_timeout: 1000, convert_timeout: 2000, launch_args: ['--font-render-hinting=medium'], wait_until: 'domcontentloaded' } # Middleware configuration config.use_pdf_middleware = true config.use_png_middleware = true config.use_jpeg_middleware = true config.ignore_path = '/assets/' config.root_url = 'https://my.external.domain' # Node.js configuration config.node_env_vars = { 'LD_PRELOAD' => '' } config.js_runtime_bin = ['node'] # Security settings config.allow_file_uris = false config.allow_local_network_access = false end ``` -------------------------------- ### Run Project Tests and Linting Source: https://github.com/studiosity/grover/blob/main/README.md Commands to execute the RSpec test suite and RuboCop linting tools. ```bash rspec rubocop ``` -------------------------------- ### Process Relative Paths in HTML Source: https://github.com/studiosity/grover/blob/main/README.md Demonstrates using Grover's HTML pre-processor to convert relative paths in HTML to absolute paths, which is crucial when Chromium needs to resolve them. ```ruby absolute_html = Grover::HTMLPreprocessor.process relative_html, 'http://my.server/', 'http' ``` -------------------------------- ### Integrate Grover Rack Middleware for Automatic Conversions Source: https://context7.com/studiosity/grover/llms.txt Add Grover's middleware to a Rack application to automatically convert HTML responses to PDF, PNG, or JPEG based on client file extension requests. This can be configured for non-Rails or Rails applications, with options for custom root URLs. ```ruby # Non-Rails Rack application (config.ru) require 'grover' use Grover::Middleware run MyApp # Rails application (config/application.rb) require 'grover' module MyApp class Application < Rails::Application config.middleware.use Grover::Middleware # Or with custom root URL config.middleware.use Grover::Middleware, root_url: 'https://my.external.domain' end end ``` -------------------------------- ### Configure Image and PDF Middleware Options Source: https://github.com/studiosity/grover/blob/main/README.md Customize the behavior of Grover's middleware for image and PDF generation. You can enable or disable middleware for PNG, JPEG, and PDF formats, and control whether specific paths or requests should be ignored. ```ruby # config/initializers/grover.rb Grover.configure do |config| config.use_png_middleware = true config.use_jpeg_middleware = true config.use_pdf_middleware = false end ``` -------------------------------- ### Inject Custom Styles and Scripts Source: https://github.com/studiosity/grover/blob/main/README.md Demonstrates how to add external CSS files or inline styles and JavaScript files or inline code to the rendered HTML content. ```ruby style_tag_options = [ { url: 'http://example.com/style.css' }, { path: 'style.css' }, { content: '.body{background: red}' } ] Grover.new('

Heading

', style_tag_options: style_tag_options).to_pdf script_tag_options = [ { url: 'http://example.com/script.js' }, { path: 'script.js' }, { content: 'document.querySelector("h1").style.display = "none"' } ] Grover.new('

Heading

', script_tag_options: script_tag_options).to_pdf ``` -------------------------------- ### Screenshot Capture (PNG and JPEG) with Grover Source: https://context7.com/studiosity/grover/llms.txt Shows how to capture screenshots of web pages or HTML content as PNG or JPEG images. This includes configuring viewport dimensions, capturing full-page screenshots, setting JPEG quality, and clipping specific areas of the page. ```ruby require 'grover' # Capture PNG screenshot from URL grover = Grover.new('https://example.com', viewport: { width: 1280, height: 720 }) png_data = grover.to_png File.open('screenshot.png', 'wb') { |f| f << png_data } # Capture JPEG with full page grover = Grover.new('https://example.com', full_page: true, quality: 80) jpeg_data = grover.to_jpeg('/path/to/screenshot.jpg') # Screenshot of inline HTML html = '

Gradient

' grover = Grover.new(html, viewport: { width: 800, height: 600 }) png_data = grover.to_png # Using screenshot method with format option grover = Grover.new('https://example.com', clip: { x: 0, y: 0, width: 400, height: 300 }) image_data = grover.screenshot(format: 'png', path: 'clipped.png') ``` -------------------------------- ### Combine PDFs via Direct Execution Source: https://github.com/studiosity/grover/blob/main/README.md Manually generates multiple PDF documents and combines them using the combine_pdf gem. This approach is useful when middleware configuration is insufficient. ```ruby require 'combine_pdf' def invoke(file_path) pdf = CombinePDF.parse(Grover.new(pdf_report_url).to_pdf) pdf >> CombinePDF.parse(Grover.new(pdf_front_cover_url).to_pdf) pdf << CombinePDF.parse(Grover.new(pdf_back_cover_url).to_pdf) pdf.save file_path end ``` -------------------------------- ### Configure Basic Authentication and Cookies for Grover Requests Source: https://context7.com/studiosity/grover/llms.txt Set up basic authentication credentials (username and password) or provide custom cookies for Grover requests to access protected pages. Cookies can be defined as an array of hashes, including domain and path, or dynamically forwarded from a Rails request. ```ruby require 'grover' # Basic authentication grover = Grover.new( 'https://protected.example.com/report', username: 'admin', password: 'secret_password' ) pdf = grover.to_pdf # Setting cookies cookies = [ { name: 'session_id', value: 'abc123', domain: 'example.com' }, { name: 'user_token', value: 'xyz789', domain: 'example.com', path: '/', secure: true } ] grover = Grover.new('https://example.com/dashboard', cookies: cookies) pdf = grover.to_pdf # Forward cookies from Rails request def header_cookies request.headers['Cookie'].split('; ').map do |cookie| key, value = cookie.split('=') { name: key, value: value, domain: request.headers['Host'] } end end grover = Grover.new('https://example.com/user/profile', cookies: header_cookies) ``` -------------------------------- ### Configure Firefox as the Rendering Engine Source: https://context7.com/studiosity/grover/llms.txt Demonstrates how to override the default Chromium engine by specifying Firefox in the Grover options. This can be applied to individual instances or configured globally for the entire application. ```ruby require 'grover' grover = Grover.new('https://example.com', browser: 'firefox') pdf = grover.to_pdf # Or configure globally Grover.configure do |config| config.options = { browser: 'firefox', executable_path: '/path/to/firefox' } end ``` -------------------------------- ### Configure Grover Middleware Behavior and Ignore Paths Source: https://context7.com/studiosity/grover/llms.txt Customize the behavior of the Grover middleware by enabling or disabling PDF, PNG, and JPEG conversions. Configure paths to be ignored based on string prefixes, regular expressions, or custom logic using procs. Requests can also be ignored based on request properties. ```ruby # Configuring middleware behavior Grover.configure do |config| config.use_pdf_middleware = true config.use_png_middleware = true config.use_jpeg_middleware = true # Ignore paths starting with string config.ignore_path = '/assets/' # Ignore paths matching regex config.ignore_path = /my\/path/ # Ignore paths via proc config.ignore_path = ->(path) { path.start_with?('/api/') } # Ignore requests via proc config.ignore_request = ->(req) { req.host == 'api.example.com' } end ``` -------------------------------- ### Middleware root_url Configuration Source: https://github.com/studiosity/grover/blob/main/README.md Configure the `root_url` option for the Grover middleware, essential when running behind a proxy or in a containerized environment. ```APIDOC ### root_url The `root_url` option can be specified either when configuring the middleware or as a global option. This is needed when running the Grover middleware behind a URL rewriting proxy or within a containerised system. As a middleware option: ```ruby # in application.rb require 'grover' config.middleware.use Grover::Middleware, root_url: 'https://my.external.domain' ``` or as a global option: ```ruby # config/initializers/grover.rb Grover.configure do |config| config.root_url = 'https://my.external.domain' end ``` ``` -------------------------------- ### Enable Grover Debugging Options Source: https://github.com/studiosity/grover/blob/main/README.md Configures Grover to display the Chromium browser window or devtools for debugging purposes. ```ruby debug: { headless: false, devtools: true } ``` -------------------------------- ### Rails Controller Integration for PDF Generation Source: https://context7.com/studiosity/grover/llms.txt This snippet demonstrates how to use Grover within a Rails controller to generate a PDF from an HTML view. It utilizes `render_to_string` for full control over the HTML content and then converts it to PDF using Grover. ```APIDOC ## POST /reports/:id/invoice ### Description Generates an invoice PDF from a Rails view using `render_to_string` and Grover. ### Method GET ### Endpoint `/reports/:id/invoice.pdf` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the invoice to generate. ### Request Body None ### Response #### Success Response (200) - **application/pdf** - The generated invoice PDF file. #### Response Example (Binary PDF data) ## GET /reports/custom.html ### Description Generates a custom report and sends it as a PDF attachment with a custom filename. ### Method GET ### Endpoint `/reports/custom.pdf` ### Parameters None ### Request Body None ### Response #### Success Response (200) - **application/pdf** - The generated custom report PDF file with a custom filename. #### Response Example (Binary PDF data) ``` -------------------------------- ### HTML Content Extraction with Grover Source: https://context7.com/studiosity/grover/llms.txt Illustrates how to retrieve the rendered HTML content from a given URL or after JavaScript execution. This is useful for debugging or capturing dynamically generated content, including the DOCTYPE. ```ruby require 'grover' # Get rendered HTML from a URL grover = Grover.new('https://example.com') html_content = grover.to_html puts html_content # => ...rendered content... # Get HTML after JavaScript execution grover = Grover.new('https://spa-app.com', wait_until: 'networkidle0') rendered_html = grover.to_html ``` -------------------------------- ### Configure Grover PDF Conversion Options via Meta Tags Source: https://context7.com/studiosity/grover/llms.txt Pass specific PDF conversion options to Grover through HTML meta tags in the head section of a document. This allows for page-specific settings when using middleware. ```html

Document Content

``` -------------------------------- ### Generate PDFs in Rails Controllers Source: https://context7.com/studiosity/grover/llms.txt This snippet demonstrates how to use render_to_string within a Rails controller to capture view output and convert it into a PDF using Grover. It handles format responses and provides options for page layout, margins, and file disposition. ```ruby class ReportsController < ApplicationController def invoice respond_to do |format| format.html { render layout: 'print' } format.pdf do html = render_to_string( template: 'reports/invoice', layout: 'print', locals: { invoice: @invoice } ) pdf = Grover.new(html, format: 'A4', margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' }, print_background: true ).to_pdf send_data pdf, filename: "invoice_#{@invoice.number}.pdf", type: 'application/pdf', disposition: 'attachment' end end end end ``` -------------------------------- ### Set Custom Environment Variables for Node.js Source: https://github.com/studiosity/grover/blob/main/README.md Configure custom environment variables for the spawned Node.js process using the `node_env_vars` option. This is useful for scenarios like disabling jemalloc in specific environments. The configuration is applied within the Grover initializer. ```ruby # config/initializers/grover.rb Grover.configure do |config| config.node_env_vars = { "LD_PRELOAD" => "" } end ``` -------------------------------- ### Generate PDF with JavaScript Execution in Ruby Source: https://github.com/studiosity/grover/blob/main/README.md Generates a PDF from a given URL, executing supplementary JavaScript code after the page has rendered but before conversion. This allows for dynamic content manipulation or interaction. ```ruby Grover.new(, execute_script: 'document.getElementsByTagName("footer")[0].innerText = "Hey"').to_pdf ``` -------------------------------- ### Allowing File URIs Source: https://github.com/studiosity/grover/blob/main/README.md Configure the `allow_file_uris` option to enable rendering HTML documents from the file system. Use with extreme caution. ```APIDOC ### allow_file_uris The `allow_file_uris` option can be used to render an HTML document from the file system. This should be used with *EXTREME CAUTION*. If used improperly it could potentially be manipulated to reveal sensitive files on the system. Do not enable if rendering content from outside entities (user uploads, external URLs, etc). It defaults to `false` preventing local system files from being read. ### Configuration ```ruby # config/initializers/grover.rb Grover.configure do |config| config.allow_file_uris = true end ``` ### Usage Example ```ruby # Grover.new accepts a file URI and optional parameters for Puppeteer grover = Grover.new('file:///some/local/file.html', format: 'A4') # Get an inline PDF of the local file pdf = grover.to_pdf ``` ``` -------------------------------- ### Configuring Grover to Use Firefox Source: https://context7.com/studiosity/grover/llms.txt This snippet shows how to configure Grover to use Firefox instead of the default Chromium browser for PDF rendering, including specifying the executable path. ```APIDOC ## Browser Configuration ### Description Configures Grover to use Firefox for rendering HTML to PDF. ### Method Configuration ### Endpoint N/A (Global Configuration) ### Parameters #### Global Configuration Options - **browser** (string) - Optional - Set to 'firefox' to use Firefox. Defaults to 'chromium'. - **executable_path** (string) - Optional - The absolute path to the Firefox executable. Required if `browser` is set to 'firefox' and not in system PATH. ### Request Example ```ruby require 'grover' # Instance-specific configuration grover = Grover.new('https://example.com', browser: 'firefox', executable_path: '/path/to/firefox') pdf = grover.to_pdf # Global configuration Grover.configure do |config| config.options = { browser: 'firefox', executable_path: '/path/to/firefox' } end ``` ### Response N/A (Configuration only) ``` -------------------------------- ### Configure Yarn PnP JS Runtime Strategy Source: https://github.com/studiosity/grover/blob/main/README.md When using the Yarn PnP strategy, you can specify the JavaScript runtime binary for Grover. This allows Grover to correctly execute JavaScript within a Yarn PnP environment. ```ruby Grover.configure do |config| config.js_runtime_bin = ['yarn', 'node'] end ``` -------------------------------- ### Yarn PnP Strategy Source: https://github.com/studiosity/grover/blob/main/README.md Override the JavaScript runtime binary when using the Yarn PnP strategy. ```APIDOC ## Yarn PnP strategy If you are using the Yarn PnP strategy, you can override the run JS runtime for grover: ### Configuration ```ruby Grover.configure do |config| config.js_runtime_bin = ['yarn', 'node'] end ``` ``` -------------------------------- ### Preprocess HTML Relative Paths Source: https://context7.com/studiosity/grover/llms.txt Converts relative asset paths in HTML strings to absolute URLs to ensure correct resource loading during PDF generation. ```ruby absolute_html = Grover::HTMLPreprocessor.process(html, 'https://my.server.com/', 'https') grover = Grover.new(absolute_html) pdf = grover.to_pdf ``` -------------------------------- ### Configure Custom Chrome Executable Path Source: https://github.com/studiosity/grover/blob/main/README.md Sets a custom path for the Chrome executable to resolve sandbox or compatibility issues. Note that this may cause version mismatch errors with Puppeteer. ```ruby executable_path: '/opt/google/chrome/chrome' ``` -------------------------------- ### Custom Environment Variables for Node Source: https://github.com/studiosity/grover/blob/main/README.md Set custom environment variables for the Node.js process spawned by Grover, such as disabling jemalloc. ```APIDOC ## Setting custom environment variable for node The `node_env_vars` configuration option enables you to set custom environment variables for the spawned node process. For example you might need to disable jemalloc in some environments (https://github.com/Studiosity/grover/issues/80). ### Configuration ```ruby # config/initializers/grover.rb Grover.configure do |config| config.node_env_vars = { "LD_PRELOAD" => "" } end ``` ``` -------------------------------- ### Middleware ignore_request Configuration Source: https://github.com/studiosity/grover/blob/main/README.md Configure the `ignore_request` option using a Proc to determine whether Grover's middleware should handle a request based on the Rack::Request object. ```APIDOC ### ignore_request The `ignore_request` configuration option can be used to tell Grover's middleware whether it should handle/modify the response. It should be set with a `Proc` which accepts the request (Rack::Request) as a parameter. ### Configuration Examples ```ruby # config/initializers/grover.rb Grover.configure do |config| # assigning a Proc config.ignore_request = ->(req) do req.host == 'www.example.com' end # matches `www.example.com/foo/bar/123.png` config.ignore_request = ->(req) do req.has_header?('X-BLOCK') end # matches `HTTP Header X-BLOCK` end ``` ``` -------------------------------- ### Configure Path Ignoring for Grover Middleware Source: https://github.com/studiosity/grover/blob/main/README.md Use the `ignore_path` configuration option to specify which request paths Grover's middleware should not handle. This can be set using a String, a Regexp, or a Proc for flexible path matching. ```ruby # config/initializers/grover.rb Grover.configure do |config| # assigning a String config.ignore_path = '/assets/' # matches `www.example.com/assets/foo.png` and not `www.example.com/bar/assets/foo.png` # assigning a Regexp config.ignore_path = /my\/path/ # matches `www.example.com/foo/my/path/bar.png` # assigning a Proc config.ignore_path = ->(path) do /\A\/foo\/.+\/[0-9]+\.png\z/.match path end # matches `www.example.com/foo/bar/123.png` end ``` -------------------------------- ### Inject Custom Scripts and Styles for HTML Conversion Source: https://context7.com/studiosity/grover/llms.txt Enhance HTML content before conversion by injecting custom JavaScript and CSS. This includes executing scripts after page load, evaluating scripts before page load, and adding external or inline styles and scripts using various configuration options. ```ruby require 'grover' # Execute JavaScript after page load grover = Grover.new( 'https://example.com', execute_script: 'document.querySelector("header").style.display = "none"' ) pdf = grover.to_pdf # Evaluate script before page loads grover = Grover.new( 'https://example.com', evaluate_on_new_document: 'window.isPDF = true; window.customConfig = { theme: "print" }' ) pdf = grover.to_pdf # Add style tags style_tag_options = [ { url: 'https://example.com/print.css' }, { path: 'local/styles/print.css' }, { content: '.no-print { display: none !important; } body { font-size: 12pt; }' } ] grover = Grover.new('

Styled

', style_tag_options: style_tag_options) # Add script tags script_tag_options = [ { url: 'https://cdn.example.com/lib.js' }, { content: 'document.body.classList.add("pdf-mode")' } ] grover = Grover.new('', script_tag_options: script_tag_options) ``` -------------------------------- ### Evaluate JavaScript on New Document in Ruby Source: https://github.com/studiosity/grover/blob/main/README.md Generates a PDF from a given URL, evaluating JavaScript code before any of the page's scripts are run. This is useful for setting global variables or modifying the page's initial state. ```ruby Grover.new(, evaluate_on_new_document: 'window.someConfig = "some value"').to_pdf ``` -------------------------------- ### Log DevTools Protocol Traffic Source: https://github.com/studiosity/grover/blob/main/README.md Sets environment variables to capture verbose DevTools protocol traffic for troubleshooting browser interactions. ```ruby Grover.configuration.node_env_vars = { 'DEBUG' => "puppeteer:*" } grover = Grover.new('Hello World') grover.to_pdf grover.debug_output ``` -------------------------------- ### Configure Root URL for Grover Middleware Source: https://github.com/studiosity/grover/blob/main/README.md Set the `root_url` option for the Grover middleware when running behind a URL rewriting proxy or within a containerized system. This ensures correct URL resolution for generated assets. ```ruby # in application.rb require 'grover' config.middleware.use Grover::Middleware, root_url: 'https://my.external.domain' ``` ```ruby # config/initializers/grover.rb Grover.configure do |config| config.root_url = 'https://my.external.domain' end ``` -------------------------------- ### Configure Local Network Access in Grover Source: https://github.com/studiosity/grover/blob/main/README.md Enables Grover to make web requests to localhost by setting the allow_local_network_access option. This is required for Puppeteer v24.16.0+ (Chrome 139+) to access local assets. ```ruby Grover.configure do |config| config.allow_local_network_access = true end ``` -------------------------------- ### Handle Conversion Errors Source: https://context7.com/studiosity/grover/llms.txt Implements rescue blocks to catch specific Grover exceptions, including request failures, JavaScript errors, and missing dependencies. ```ruby begin grover = Grover.new('https://example.com', raise_on_request_failure: true, raise_on_js_error: true) pdf = grover.to_pdf rescue Grover::JavaScript::RequestFailedError => e puts "Request failed: #{e.message}" rescue Grover::JavaScript::PageRenderError => e puts "JavaScript error: #{e.message}" rescue Grover::DependencyError => e puts "Missing dependency: #{e.message}" end ``` -------------------------------- ### Customize PDF Headers and Footers with Dynamic Content Source: https://context7.com/studiosity/grover/llms.txt Define custom HTML templates for PDF headers and footers using Grover. These templates can include dynamic elements like page numbers, total pages, dates, document titles, and URLs, allowing for rich and informative document generation. ```ruby require 'grover' header_template = <<~HTML
HTML footer_template = <<~HTML
Page of
HTML grover = Grover.new( 'https://example.com/report', format: 'A4', display_header_footer: true, header_template: header_template, footer_template: footer_template, margin: { top: '50px', bottom: '50px' } ) pdf = grover.to_pdf ``` -------------------------------- ### Middleware ignore_path Configuration Source: https://github.com/studiosity/grover/blob/main/README.md Configure the `ignore_path` option to control which request paths the Grover middleware should handle. ```APIDOC ### ignore_path The `ignore_path` configuration option can be used to tell Grover's middleware whether it should handle/modify the response. There are three ways to set up the `ignore_path`: * a `String` which matches the start of the request path. * a `Regexp` which could match any part of the request path. * a `Proc` which accepts the request path as a parameter. ### Configuration Examples ```ruby # config/initializers/grover.rb Grover.configure do |config| # assigning a String config.ignore_path = '/assets/' # matches `www.example.com/assets/foo.png` and not `www.example.com/bar/assets/foo.png` # assigning a Regexp config.ignore_path = /my\/path/ # matches `www.example.com/foo/my/path/bar.png` # assigning a Proc config.ignore_path = ->(path) do /\A\/foo\/.+\/[0-9]+\.png\z/.match path end # matches `www.example.com/foo/bar/123.png` end ``` ``` -------------------------------- ### Configure AppArmor for Puppeteer Headless Shell Source: https://github.com/studiosity/grover/blob/main/README.md Creates an AppArmor profile specifically for the chrome-headless-shell binary managed by Puppeteer. ```shell export CHROME_HEADLESS_SHELL_PATH=$(find ~/.cache/puppeteer/chrome-headless-shell/ -executable -type f -name chrome-headless-shell -print -quit) cat | sudo tee /etc/apparmor.d/chrome-headless-shell <, include profile chrome-headless-shell $CHROME_HEADLESS_SHELL_PATH flags=(unconfined) { userns, include if exists } EOF sudo service apparmor reload ``` -------------------------------- ### Connect to Remote Browser Instance Source: https://context7.com/studiosity/grover/llms.txt Connects Grover to a remote Chromium instance, such as a browserless container, using a WebSocket endpoint. ```ruby grover = Grover.new('https://example.com', browser_ws_endpoint: 'ws://localhost:3000/chrome') pdf = grover.to_pdf grover = Grover.new('https://example.com', browser_ws_endpoint: 'ws://localhost:3000/chrome?--disable-speech-api') png = grover.to_png('/path/to/screenshot.png') ``` -------------------------------- ### Configure Request Ignoring for Grover Middleware Source: https://github.com/studiosity/grover/blob/main/README.md Define conditions for Grover's middleware to ignore requests using the `ignore_request` configuration option. This option accepts a Proc that takes a Rack::Request object and returns true if the request should be ignored. ```ruby # config/initializers/grover.rb Grover.configure do |config| # assigning a Proc config.ignore_request = ->(req) do req.host == 'www.example.com' end # matches `www.example.com/foo/bar/123.png` config.ignore_request = ->(req) do req.has_header?('X-BLOCK') end # matches `HTTP Header X-BLOCK` end ``` -------------------------------- ### Debug Rendering and DevTools Source: https://context7.com/studiosity/grover/llms.txt Configures debugging options to disable headless mode or capture DevTools protocol traffic for troubleshooting. ```ruby grover = Grover.new('https://example.com', debug: { headless: false, devtools: true }) Grover.configure { |config| config.node_env_vars = { 'DEBUG' => 'puppeteer:*' } } grover = Grover.new('https://example.com') pdf = grover.to_pdf ``` -------------------------------- ### Combine PDF Documents Source: https://context7.com/studiosity/grover/llms.txt Uses the combine_pdf gem to merge multiple PDF outputs into a single document, useful for adding cover pages. ```ruby pdf = CombinePDF.new pdf >> CombinePDF.parse(Grover.new('/covers/front').to_pdf) pdf << CombinePDF.parse(Grover.new('https://example.com/report').to_pdf) pdf << CombinePDF.parse(Grover.new('/covers/back').to_pdf) pdf.save('final_report.pdf') ``` -------------------------------- ### Set Custom PDF Filename in Rails Controller Source: https://github.com/studiosity/grover/blob/main/README.md Shows how to set the content-disposition header in a Rails controller to define the filename for a generated PDF. ```ruby respond_to do |format| format.html do response.headers['content-disposition'] = %(attachment; filename="lorem_ipsum.pdf") render layout: 'pdf' end end ``` -------------------------------- ### Configure AppArmor for Puppeteer Chrome Source: https://github.com/studiosity/grover/blob/main/README.md Creates an AppArmor profile to allow the Puppeteer-managed Chrome executable to run with unconfined user namespace permissions. ```shell export PUPPETEER_CHROME_PATH=$(node -e "console.log(require('puppeteer').executablePath())") cat | sudo tee /etc/apparmor.d/chrome <, include profile chrome $PUPPETEER_CHROME_PATH flags=(unconfined) { userns, include if exists } EOF sudo service apparmor reload ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.