### Define Basic PDF Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Demonstrates how to create a basic PDF component by subclassing `Phlex::PDF` and implementing the `view_template` method for rendering logic. Includes an example of a simple text component with customization and generating a PDF. ```ruby require "phlex/pdf" # Base component class for shared functionality class PDFComponent < Phlex::PDF end # Simple text component with customization class WarningComponent < PDFComponent def initialize(message) @message = message end def view_template text @message, color: "FF0000" end end # Generate PDF with the component WarningComponent.new("This is a warning!").to_pdf ``` -------------------------------- ### Render Nested Components in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Illustrates composing multiple PDF components together, including passing blocks to components and rendering collections. This example defines header, box, and footer components, composing them into a `ComplexPage`. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page end # Header component class HeaderComponent < PDFComponent def view_template text "Company Report", size: 24, align: :center move_down 20 end end # Box component that yields to blocks class BoxComponent < PDFComponent def view_template stroke_bounds do pad(10) do text "Box Content:" yield if block_given? end end end end # Footer component class FooterComponent < PDFComponent def view_template move_down 20 text "Page #{document.page_number}", align: :right end end # Complete page with nested components class ComplexPage < PDFPage def initialize(title:, items:) @title = title @items = items end def view_template render HeaderComponent.new text @title, size: 18, style: :bold move_down 10 render BoxComponent.new do text "This content is inside the box" @items.each { |item| text "• #{item}" } end render FooterComponent.new end end # Generate PDF ComplexPage.new( title: "Quarterly Results", items: ["Revenue up 15%", "Costs down 5%", "Profit margin improved"] ).to_pdf ``` -------------------------------- ### Create Page Component with Lifecycle Hooks in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Shows how to create page components using `before_template` and `after_template` hooks for automatic page creation and adding elements like page numbers. This example defines a base page class and a specific report page implementation. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end # Base page class with automatic page creation class PDFPage < PDFComponent # Creates a new page before rendering template def before_template start_new_page end # Adds page number after rendering template def after_template text "Page #{document.page_number}" end end # Specific page implementation class ReportPage < PDFPage def initialize(title:) @title = title end def view_template text @title, size: 24, style: :bold text "Report content goes here" end end # Render to PDF string pdf_content = ReportPage.new(title: "Monthly Report").to_pdf # Save to file File.write("report.pdf", pdf_content) ``` -------------------------------- ### Multi-Page Document Generation Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Learn how to construct multi-page documents by rendering page components sequentially. Includes examples of adding page numbers and chapter content. ```APIDOC ## Multi-Page Document Generation ### Description This section details how to create multi-page PDF documents by rendering individual page components in sequence. It also demonstrates adding dynamic elements like page numbers and structured chapter content. ### Method ```ruby render @chapters.map.with_index do |chapter, index| ChapterPage.new( chapter_number: index + 1, title: chapter[:title], content: chapter[:content] ) end ``` ### Example Usage ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page def after_template text "Page #{document.page_number}", align: :right, size: 10 end end class ChapterPage < PDFPage def initialize(chapter_number:, title:, content:) @chapter_number = chapter_number @title = title @content = content end def view_template text "Chapter #{@chapter_number}", size: 24, style: :bold move_down 10 text @title, size: 18 move_down 20 text @content, align: :justify end end class BookDocument < PDFComponent def initialize(chapters:) @chapters = chapters end def view_template render @chapters.map.with_index do |chapter, index| ChapterPage.new( chapter_number: index + 1, title: chapter[:title], content: chapter[:content] ) end end end # Generate multi-page book chapters = [ { title: "The Beginning", content: "Once upon a time..." }, { title: "The Middle", content: "And then things happened..." }, { title: "The End", content: "They lived happily ever after." } ] pdf_content = BookDocument.new(chapters: chapters).to_pdf File.write("book.pdf", pdf_content) ``` ``` -------------------------------- ### Multi-Page Document Generation with Phlex::PDF Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Explains how to create multi-page PDF documents by sequentially rendering page components. It includes a `PDFPage` base class that automatically starts a new page before rendering and adds page numbers. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page def after_template text "Page #{document.page_number}", align: :right, size: 10 end end class ChapterPage < PDFPage def initialize(chapter_number:, title:, content:) @chapter_number = chapter_number @title = title @content = content end def view_template text "Chapter #{@chapter_number}", size: 24, style: :bold move_down 10 text @title, size: 18 move_down 20 text @content, align: :justify end end class BookDocument < PDFComponent def initialize(chapters:) @chapters = chapters end def view_template render @chapters.map.with_index do |chapter, index| ChapterPage.new( chapter_number: index + 1, title: chapter[:title], content: chapter[:content] ) end end end # Generate multi-page book chapters = [ { title: "The Beginning", content: "Once upon a time..." }, { title: "The Middle", content: "And then things happened..." }, { title: "The End", content: "They lived happily ever after." } ] pdf_content = BookDocument.new(chapters: chapters).to_pdf File.write("book.pdf", pdf_content) ``` -------------------------------- ### Define Base and Page Components in Ruby Source: https://github.com/phlex-ruby/phlex-pdf/blob/main/README.md Demonstrates the creation of a base PDF component and a page component. The base component is for shared methods, while the page component handles page creation and numbering. It sets up the fundamental structure for PDF generation. ```ruby require "phlex/pdf" # Base component. You'll put methods here that are shared across all components. class PDFComponent < Phlex::PDF end # Page has a `before_template` method that created a new page. Without a page # nothing will render and an error would occur. class PDFPage < PDFComponent # Creates a new page def before_template = create_new_page def after_template text "Page #{document.page_number}" end end # Example component inherits from PDFComponent. Note that it does NOT create any # new pages. class BoxComponent < PDFComponent def view_template text "I'm a box" yield end end # The final PDF that's rendered should be a subclass of PDFPage. Components # can be rendered within a PDFPage. class MyPage < PDFPage def initialize(title:) @title = title end def view_template text @title render BoxComponent.new do text "Look! I'm a box inside a box!" end end end # Render the PDF to a string. MyPage.new(title: "This is a PDF!").to_pdf ``` -------------------------------- ### Generate an Invoice PDF in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This snippet shows how to instantiate and generate an invoice PDF. It creates an `InvoicePage` object with sample data and then uses `to_pdf` to generate the PDF content, which is subsequently saved to a file named `invoice.pdf`. ```ruby # Generate invoice invoice = InvoicePage.new( invoice_number: "INV-2024-001", customer: "Acme Corp", line_items: [ { name: "Widget A", qty: 5, price: 10.00 }, { name: "Widget B", qty: 3, price: 15.00 }, { name: "Service Fee", qty: 1, price: 50.00 } ] ) File.write("invoice.pdf", invoice.to_pdf) ``` -------------------------------- ### Advanced Reusable Table Component with Custom Methods Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Illustrates the creation of a reusable `TableComponent` using Phlex::PDF. This component leverages Prawn's table functionality and demonstrates how to define custom methods within a component that can be called from its template. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page end # Table component with helper methods class TableComponent < PDFComponent def initialize(headers:, rows:) @headers = headers @rows = rows end def view_template # Create table using Prawn's table method table([[@headers] + @rows].flatten(1)) do row(0).font_style = :bold row(0).background_color = "EEEEEE" end end end ``` -------------------------------- ### Create an Invoice Page Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This code defines an `InvoicePage` component that inherits from `PDFPage`. It takes invoice details and line items, then renders a header with the invoice number and customer, followed by a table of line items and the total amount. It demonstrates component composition by using `TableComponent`. ```ruby class InvoicePage < PDFPage def initialize(invoice_number:, customer:, line_items:) @invoice_number = invoice_number @customer = customer @line_items = line_items end def view_template text "Invoice ##{@invoice_number}", size: 24, style: :bold text "Customer: #{@customer}" move_down 20 render TableComponent.new( headers: ["Item", "Quantity", "Price", "Total"], rows: @line_items.map do |item| [item[:name], item[:qty], "$#{item[:price]}", "$#{item[:qty] * item[:price]}"] end ) move_down 20 total = @line_items.sum { |item| item[:qty] * item[:price] } text "Total: $#{total}", size: 16, style: :bold, align: :right end end ``` -------------------------------- ### Create a Branded Page Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This snippet defines `BrandedPage`, which extends `BrandedComponent` to include a header and footer on every page. It utilizes lifecycle hooks (`before_template`, `after_template`) to draw a company header with a colored background and a footer with copyright information and page numbers. ```ruby # Branded page with company header class BrandedPage < BrandedComponent def before_template start_new_page draw_header end def after_template draw_footer end private def draw_header bounding_box([0, cursor], width: bounds.width, height: 50) do fill_color BRAND_COLOR fill_rectangle [0, 50], bounds.width, 50 fill_color "FFFFFF" text_box "Company Name", at: [10, 40], size: 18, style: :bold fill_color "000000" end move_down 60 end def draw_footer move_to_bottom = bounds.bottom + 30 bounding_box([0, move_to_bottom], width: bounds.width, height: 30) do text "© 2024 Company Name | Page #{document.page_number}", align: :center, size: 10, color: "666666" end end end ``` -------------------------------- ### Generate a Branded Sales Report PDF in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This snippet demonstrates generating a PDF sales report. It instantiates `SalesReport` with specific period and sales data, then calls `to_pdf` to produce the PDF content, saving it to `sales_report.pdf`. This showcases the full integration of branded components. ```ruby # Generate branded report report = SalesReport.new( period: "Q4 2024", sales_data: { "North America" => 150_000, "Europe" => 120_000, "Asia Pacific" => 180_000 } ) File.write("sales_report.pdf", report.to_pdf) ``` -------------------------------- ### Rendering Multiple Component Types Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Demonstrates how to render different Ruby objects like strings, arrays, procs, lambdas, and methods directly within your PDF components. ```APIDOC ## Rendering Multiple Component Types ### Description This section showcases the flexibility of Phlex::PDF in rendering various Ruby objects, including strings, arrays, procs, lambdas, and methods, as components within a PDF document. ### Method ```ruby render "Direct string rendering" render [ WarningComponent.new("First warning"), WarningComponent.new("Second warning") ] render Proc.new { text "From Proc.new", color: "00FF00" } render lambda { text "From lambda", color: "0000FF" } render -> { text "From stabby lambda", color: "FF00FF" } render method(:custom_method) render BodyComponent.new do |body| body.custom_text("Hello from block") end ``` ### Example Usage ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page end class FlexiblePage < PDFPage def initialize(title:) @title = title end def view_template render "Direct string rendering" render [ WarningComponent.new("First warning"), WarningComponent.new("Second warning") ] render Proc.new { text "From Proc.new", color: "00FF00" } render lambda { text "From lambda", color: "0000FF" } render -> { text "From stabby lambda", color: "FF00FF" } render method(:custom_method) render BodyComponent.new do |body| body.custom_text("Hello from block") end end def custom_method text "Rendered from method", style: :italic end end class WarningComponent < PDFComponent def initialize(message) @message = message end def view_template text @message, color: "FF0000" end end class BodyComponent < PDFComponent def view_template yield self if block_given? end def custom_text(content) text content, size: 14 end end # Generate PDF with multiple rendering types FlexiblePage.new(title: "Mixed Content").to_pdf ``` ``` -------------------------------- ### Rails Controller Integration for PDF Generation Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Shows how to integrate Phlex::PDF with Rails controllers using `Phlex::PDF::Rails::Helpers`. This enables sending generated PDFs directly to the browser as inline content or attachments with customizable filenames and content types. ```ruby # app/controllers/reports_controller.rb class ReportsController < ApplicationController include Phlex::PDF::Rails::Helpers def show @report = Report.find(params[:id]) # Send PDF inline (display in browser) send_pdf ReportPage.new( title: @report.title, data: @report.data ) end def download @report = Report.find(params[:id]) # Send PDF as attachment (force download) send_pdf( ReportPage.new(title: @report.title, data: @report.data), disposition: "attachment", filename: "report-#{@report.id}.pdf" ) end def preview @report = Report.find(params[:id]) # Custom type and additional options send_pdf( ReportPage.new(title: @report.title, data: @report.data), disposition: "inline", type: "application/pdf", filename: "preview-#{Date.today}.pdf" ) end end # Component definition class ReportPage < Phlex::PDF def initialize(title:, data:) @title = title @data = data end def before_template = start_new_page def view_template text @title, size: 24, style: :bold move_down 20 @data.each do |key, value| text "#{key}: #{value}" end end end ``` -------------------------------- ### Rendering Multiple Ruby Object Types as PDF Components Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Demonstrates how to render various Ruby objects, such as strings, arrays, procs, lambdas, and methods, directly within a Phlex::PDF component. This allows for flexible content generation within your PDF. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page end class FlexiblePage < PDFPage def initialize(title:) @title = title end def view_template # Render string directly render "Direct string rendering" # Render array of components render [ WarningComponent.new("First warning"), WarningComponent.new("Second warning") ] # Render proc render Proc.new { text "From Proc.new", color: "00FF00" } # Render lambda render lambda { text "From lambda", color: "0000FF" } # Render stabby lambda render -> { text "From stabby lambda", color: "FF00FF" } # Render method render method(:custom_method) # Render component with block parameter render BodyComponent.new do |body| body.custom_text("Hello from block") end end def custom_method text "Rendered from method", style: :italic end end class WarningComponent < PDFComponent def initialize(message) @message = message end def view_template text @message, color: "FF0000" end end class BodyComponent < PDFComponent def view_template yield self if block_given? end def custom_text(content) text content, size: 14 end end # Generate PDF with multiple rendering types FlexiblePage.new(title: "Mixed Content").to_pdf ``` -------------------------------- ### Define a Sales Report Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This `SalesReport` component inherits from `BrandedPage`, incorporating the shared branding and page structure. Its `view_template` renders a branded heading, period information, and a list of sales data by region, demonstrating the use of inherited methods like `brand_heading`. ```ruby # Specific report using branded components class SalesReport < BrandedPage def initialize(period:, sales_data:) @period = period @sales_data = sales_data end def view_template brand_heading "Sales Report" brand_text "Period: #{@period}" move_down 20 @sales_data.each do |region, amount| text "#{region}: $#{amount}", size: 14 end end end ``` -------------------------------- ### Rails Controller Integration for Sending PDFs Source: https://github.com/phlex-ruby/phlex-pdf/blob/main/README.md Shows how to integrate Phlex::PDF with a Rails controller to send generated PDFs. It utilizes the `send_pdf` helper, which is a convenience wrapper around Rails' `send_data` method, to stream the PDF content to the client. ```ruby class MyController < ApplicationController include Phlex::PDF::Rails::Helpers def show send_pdf MyPage.new(title: "This is a PDF!") end end ``` -------------------------------- ### Advanced Component with Custom Methods Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Create sophisticated and reusable PDF components by defining custom helper methods that can be invoked from within component blocks, such as generating tables. ```APIDOC ## Advanced Component with Custom Methods ### Description This section demonstrates how to build advanced, reusable PDF components by defining custom helper methods. These methods can be called from within the component's template or from blocks, enabling complex structures like dynamic tables. ### Example: Table Component This example shows a `TableComponent` that utilizes Prawn's table functionality and customizes rows. ```ruby require "phlex/pdf" class PDFComponent < Phlex::PDF end class PDFPage < PDFComponent def before_template = start_new_page end # Table component with helper methods class TableComponent < PDFComponent def initialize(headers:, rows:) @headers = headers @rows = rows end def view_template # Create table using Prawn's table method table([[@headers] + @rows].flatten(1)) do row(0).font_style = :bold row(0).background_color = "EEEEEE" end end end ``` ``` -------------------------------- ### Define a Base Branded Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This code defines a `BrandedComponent` that inherits from `Phlex::PDF`. It establishes `BRAND_COLOR` and `ACCENT_COLOR` constants and provides helper methods (`brand_heading`, `brand_text`) for consistent application of these brand colors to text elements within PDF documents. ```ruby require "phlex/pdf" # Base component with shared styling class BrandedComponent < Phlex::PDF BRAND_COLOR = "1E40AF" ACCENT_COLOR = "3B82F6" def brand_heading(text) text text, size: 20, color: BRAND_COLOR, style: :bold end def brand_text(text) text text, color: BRAND_COLOR end end ``` -------------------------------- ### Rails Controller Integration Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt Integrate Phlex::PDF with Rails controllers to send PDFs directly to the browser, supporting inline display or file downloads with customizable options. ```APIDOC ## Rails Controller Integration ### Description This section explains how to integrate Phlex::PDF components within Rails controllers. It covers sending PDFs directly to the browser with appropriate content types and disposition settings, including inline viewing and forced downloads. ### Methods - `send_pdf(template, **options)`: Sends a Phlex::PDF component as a PDF response. - `disposition:`: Controls whether the PDF is displayed inline (`"inline"`) or downloaded (`"attachment"`). Defaults to `"inline"`. - `filename:`: Specifies the filename for downloaded PDFs. - `type:`: Sets the MIME type for the response. Defaults to `"application/pdf"`. ### Example Usage in Rails Controller ```ruby # app/controllers/reports_controller.rb class ReportsController < ApplicationController include Phlex::PDF::Rails::Helpers def show @report = Report.find(params[:id]) # Send PDF inline (display in browser) send_pdf ReportPage.new( title: @report.title, data: @report.data ) end def download @report = Report.find(params[:id]) # Send PDF as attachment (force download) send_pdf( ReportPage.new(title: @report.title, data: @report.data), disposition: "attachment", filename: "report-#{@report.id}.pdf" ) end def preview @report = Report.find(params[:id]) # Custom type and additional options send_pdf( ReportPage.new(title: @report.title, data: @report.data), disposition: "inline", type: "application/pdf", filename: "preview-#{Date.today}.pdf" ) end end # Component definition class ReportPage < Phlex::PDF def initialize(title:, data:) @title = title @data = data end def before_template = start_new_page def view_template text @title, size: 24, style: :bold move_down 20 @data.each do |key, value| text "#{key}: #{value}" end end end ``` ``` -------------------------------- ### Define a Bar Chart Component in Ruby Source: https://context7.com/phlex-ruby/phlex-pdf/llms.txt This snippet defines a `BarChartComponent` that inherits from `PDFComponent`. It takes a title and data, then draws text and rectangles to represent a bar chart. It uses private methods for drawing individual bars and customizes colors and positioning. ```ruby class BarChartComponent < PDFComponent def initialize(title:, data:) @title = title @data = data end def view_template text @title, size: 16, style: :bold move_down 10 @data.each do |label, value| draw_bar(label, value) move_down 5 end end private def draw_bar(label, value) text label stroke_color "0000FF" fill_color "0000FF" fill_rectangle [100, cursor], value * 2, 10 fill_color "000000" end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.