require 'pdf/writer' require 'spec/story/runner/story_parser.rb' module PDF module Storycards class Writer CARD_WIDTH = PDF::Writer.in2pts(5) CARD_HEIGHT = PDF::Writer.in2pts(3) def self.make_pdf( story_text, opts ) opts[:style] = :card_1up unless opts[:style] opts[:borders] = false unless opts[:borders] stories = StoryParser.new.parse_stories(story_text) if opts[:style] == :card_1up pdf = PDF::Writer.new(:paper => [7.62, 12.7], :orientation => :landscape) #3x5 card pdf.margins_mm 8 pdf.move_pointer(-60) stories.each_with_index do |story, index| pdf.start_new_page if index > 0 print_card_corners(pdf, story, opts[:lower_left], opts[:lower_right], 0, 0) print_card_text(pdf, story, 0, opts[:make_sentences]) end return pdf.render elsif opts[:style] == :letter_4up pdf = PDF::Writer.new(:paper => "LETTER", :orientation => :landscape) margin = PDF::Writer.in2pts(0.33) gutter = margin padding = 10 pdf.start_columns(2, gutter) stories.each_with_index do |story, index| is_laying_out_left_hand_column = (index % 4 < 2) if is_laying_out_left_hand_column rect_x = margin else rect_x = pdf.page_width - margin - CARD_WIDTH end is_laying_out_top_row = (index % 2 == 0) if is_laying_out_top_row pdf.start_new_page unless index == 0 pdf.y = pdf.page_height - margin - padding rect_y = pdf.page_height - margin - CARD_HEIGHT else rect_y = margin pdf.y = margin + CARD_HEIGHT - padding end print_border(pdf, rect_x, rect_y) if opts[:borders] print_card_corners(pdf, story, opts[:lower_left], opts[:lower_right], rect_x, rect_y) print_card_text(pdf, story, padding, opts[:make_sentences]) end return pdf.render else raise "Unknown style: #{opts[:style]}" end end private def self.print_border(pdf, x, y) pdf.stroke_color(Color::RGB::Black) pdf.stroke_style(PDF::Writer::StrokeStyle.new(1)) pdf.rectangle(x, y, CARD_WIDTH, CARD_HEIGHT).close_stroke end def self.print_card_text(pdf, story, padding = 0, make_sentences = false) top = pdf.y pdf.text "#{story.title}", :font_size => 18, :justification => :center, :left => padding, :right => padding pdf.move_pointer(12) narrative = story.narrative narrative = narrative.to_sentence if make_sentences pdf.text narrative, :justification => :left, :font_size => 14, :left => padding, :right => padding end def self.print_card_corners(pdf, story, lower_left_meta_data_key, lower_right_meta_data_key, card_x, card_y) text_y = card_y + 16 + 8 text_width = CARD_WIDTH/2 - PDF::Writer.in2pts(0.4) if story.meta_data[lower_left_meta_data_key] text_x = card_x + PDF::Writer.in2pts(0.4) pdf.add_text_wrap text_x, text_y, text_width, story.meta_data[lower_left_meta_data_key], 16, :left end if story.meta_data[lower_right_meta_data_key] text_x = card_x + CARD_WIDTH/2 pdf.add_text_wrap text_x, text_y, text_width, story.meta_data[lower_right_meta_data_key], 16, :right end end end end end