I have read through all relevant posts on Prawn but found no mentioning (even in Prawn's own documentation) of headers and footers.
However, I did see a demo on Prawnto's own website about headers and footers. I copied the entire source of that demo just to see if it works but an error of undefined method "header" is complained about. Am I to understand that Prawn took out header and footer recently in the gem or is there something else I need to do first to use header and footer?
The demo page:
http://cracklabs.com/prawnto/code/prawn_demos/source/text/flowing_text_with_header_and_footer
the part of code of concern:
Prawn::Document.generate("flow_with_headers_and_footers.pdf") do
header margin_box.top_left do
text "Here's My Fancy Header", :size => 25, :align => :center
end
text "hello world!"
end
And by header, just in case, I mean the snippets of words that appear usually at a corner of every page of a document. Like your account number in your bills pages.
thanks!
The sample you are refering to, from the prawnto plugin, is using an older version of prawn.
Since i also needed header and footer i looked a bit more into this. It seems that that version of prawn had header and footer methods, which were implemented using lazy bounding box. (found by checking the code on github)
In the new prawn version you can do the same thing using repeaters.
Here is the full sample rewritten using the new version:
require "#{File.dirname(__FILE__)}/../example_helper.rb"
Prawn::Document.generate("test.pdf") do
repeat :all do
# header
bounding_box [bounds.left, bounds.top], :width => bounds.width do
font "Helvetica"
text "Here's My Fancy Header", :align => :center, :size => 25
stroke_horizontal_rule
end
# footer
bounding_box [bounds.left, bounds.bottom + 25], :width => bounds.width do
font "Helvetica"
stroke_horizontal_rule
move_down(5)
text "And here's a sexy footer", :size => 16
end
end
bounding_box([bounds.left, bounds.top - 50], :width => bounds.width, :height => bounds.height - 100) do
text "this is some flowing text " * 200
move_down(20)
font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
table [["ὕαλον ϕαγεῖν", "baaar", "1" ],
["This is","a sample", "2" ],
["Table", "dont\ncha\nknow?", "3" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules\nwith an iron fist", "x" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ]],
:font_size => 24,
:horizontal_padding => 10,
:vertical_padding => 3,
:border_width => 2,
:position => :center,
:headers => ["Column A","Column B","#"]
end
end
you can check the documentation page of repeat for other options which allow you to exactly specify where you want the repeaters.
#GrantSayer thx for the example, but this will only let you show the current page number, not the total number of pages.
You can also use the number_pages function for the footer:
Prawn::Document.generate("page_with_numbering.pdf") do
text "Hai"
start_new_page
text "bai"
start_new_page
text "-- Hai again"
number_pages "<page> in a total of <total>", [bounds.right - 50, 0]
end
However, in my case I also need to format/style and right align the page numbers to match company style guides. I used go_to_page(k) to create my own header and footer functions, which add the header and footer to each page after all the pages are created. This gives me both styling options and the total number of pages:
Prawn::Document.generate("footer_example.pdf", :skip_page_creation => true) do
10.times do
start_new_page
text "Some filler text for the page"
end
# footer
page_count.times do |i|
go_to_page(i+1)
lazy_bounding_box([bounds.right-50, bounds.bottom + 25], :width => 50) {
text "#{i+1} / #{page_count}"
}.draw
end
end
It's little bit different with latest version of Prawn you must passe an hash
Prawn::Document.generate("page_with_numbering.pdf") do
text "Hai"
start_new_page
text "bai"
start_new_page
text "-- Hai again"
number_pages "<page> in a total of <total>", { :start_count_at => 0, :page_filter => :all, :at => [bounds.right - 50, 0], :align => :right, :size => 14 }
end
If you want a footer that do not write stuff over your text, you have to create the bounding_box below the margin of the document using bounds.bottom.
require 'prawn'
file_name = 'hello.pdf'
random_table = (0..50).map{|i|[*('a'..'z')]} # generate a 2D array for example (~2 pages)
Prawn::Document::generate(file_name) do |pdf|
pdf.table random_table
pdf.page_count.times do |i|
pdf.bounding_box([pdf.bounds.left, pdf.bounds.bottom], :width => pdf.bounds.width, :height => 30) {
# for each page, count the page number and write it
pdf.go_to_page i+1
pdf.move_down 5 # move below the document margin
pdf.text "#{i+1}/#{pdf.page_count}", :align => :center # write the page number and the total page count
}
end
end
It should look like that, you can see that the footer is outside the margin bottom :
Hope it help someone
START EDIT
This works in prawn >= 0.12
END EDIT
Here is my solution using repeat, canvas and cell. Essentially I'm drawing my bounding boxes at the absolute top and bottom of every page. I'm using cell to have better styling control over it. Hope this is going to be helpful to someone. ( I used slightly annoying colors to better illustrate how you can control styling of header and footer)
Prawn::Document.generate("headers_and_footers_with_background.pdf") do
repeat :all do
# header
canvas do
bounding_box([bounds.left, bounds.top], :width => bounds.width) do
cell :content => 'Header',
:background_color => 'EEEEEE',
:width => bounds.width,
:height => 50,
:align => :center,
:text_color => "001B76",
:borders => [:bottom],
:border_width => 2,
:border_color => '00FF00',
:padding => 12
end
end
# footer
canvas do
bounding_box [bounds.left, bounds.bottom + 50], :width => bounds.width do
cell :content => 'Footer',
:background_color => '333333',
:width => bounds.width,
:height => 50,
:align => :center,
:text_color => "FFFFFF",
:borders => [:top],
:border_width => 2,
:border_color => 'FF0000',
:padding => 12
end
end
end
# body
bounding_box([bounds.left, bounds.top - 25], :width => bounds.width, :height => bounds.height - 50) do
100.times do
text "Some filler text for the page"
end
end
end
here's the problem when using the bounding_box for creating the custom footer contents... it is still rendering within the bounds of a margin.
I was looking for something that will write the contents in the margin area together with number_pages.(because a footer usually is set in the bottom margin area)... and it seems that there were none.
so instead, I used text_box and place the coordinates outside my main bounding box like so:
repeat :all do
text_box "My custom footer", size: 7, align: :center, :at => [bounds.left, bounds.bottom], :height => 100, :width => bounds.width
end
take note that the repeat :all , will render this footer text to every page.
The only way I've found to get a repeating item on a page is to use the Prawn::Document::LazyBoundingBox method. Basically this allows you to define a bounding box that is only rendered once you call it. So the usual pseudo-code steps are
Define lazy bounding box element assign to somevar
On each new page call the element.
The example from the source shows how
file = "lazy_bounding_boxes.pdf"
Prawn::Document.generate(file, :skip_page_creation => true) do
point = [bounds.right-50, bounds.bottom + 25]
page_counter = lazy_bounding_box(point, :width => 50) do
text "Page: #{page_count}"
end
10.times do
start_new_page
text "Some filler text for the page"
page_counter.draw
end
end
This gives you a Page-count text output on each new page. What would be ideal is if this could be applied in the setup of a page template that is reused without the manual call to render the element. Combined with text flow this would give the traditional solution of headers and footers.
Related
As a source file I have a square image (500x500).
As soon as I use the cropArea, the preview shows that the entire area has been selected (500x500px)
'cropVariants' => [
'default' => [
'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.crop_variant.default',
'allowedAspectRatios' => [
'1:1' => [
'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.1_1',
'value' => 1.0
]
],
'selectedRatio' => '1:1',
'cropArea' => [
'x' => 0.0,
'y' => 0.0,
'width' => 1.0,
'height' => 1.0,
],
],
],
But in the database, however, the following data (sys_file_reference) is stored: (problem y-coordinate)
{"default":{"cropArea":{"height":1,"width":1,"x":0,"y":-0.002},"selectedRatio":"1:1","focusArea":null}}
In Fluid this is my code:
<f:image src="{item.image.0.reference.uid}" alt="{item.image.0.reference.description}" treatIdAsReference="1" />
As a result that image is rendered in fluid with 500 x 499 pixels. (1px is missing)
Any idea how I can adjust the behavior? so that the y-coordinate is also set to 0 and the whole selection is rendered?
I am using ruby, and attempting to get referrals from google analytics api. Here is what I have set up:
sa_referral = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + saprofileID,
'dimensions' => "ga:fullreferrer",
'metrics' => "ga:users",
'sort' => "-ga:users",
'filters' => "ga:source!=(direct);",
'start-date' => startDate,
'end-date' => endDate,
})
sa_referral_data = sa_referral do |row|
row = {
:referral => row['0'],
:members => row['1'],
}
end
send_event('sa_top_referrals', current: sa_referral_data)
This returns no data when called in the widget using sa_top_referrals. Below is the data the API is returning.
"columnHeaders": [
{
"name": "ga:fullreferrer",
"columnType": "DIMENSION",
"dataType": "STRING"
},
{
"name": "ga:users",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"totalsForAllResults": {
"ga:users": "35638"
},
"rows": [
[
"m.facebook.com/",
"1009"
],
[
"baidu",
"912"
],
[
"usasexguide.info/forum/showthread.php",
"613"
],
Ideally the information I am looking to pull down is the URL ex: m.facebook.com/ and the user count or "613". Those are the two items I am looking to pull. My question is how do I know what row those are equal to. Above i'm sending it using: :referral => row['0'], I'd assume the issue is that its not actually row 0, is there a way I can confirm this?
This should do it:
sa_referral_data = sa_referral['rows'] do |row|
rows.map{|r| { referrals:r[0], members:r[1] }}
end
I have the following table code:
member_id_and_first_name_and_nps_score_and_comments = [["14169021-00",
"Chris", 9, "YMCA in the Tampa, FL area is fantastic. I would like to
see the level of support for other sports also provided to
racquetball."], ["1660592-00", "Nayrone", 9, "There are so many
offerings for activities and there are many convenient locations
throughout the area."], ["16183029-00", "Mary", 9, "I like the staff
but the showers are gross"], ["16257833-00", "Phyllis", 10, "A
comfortable environment, a place where you can meet people and most
importantly the staff is always available."], ["1629846-00", "Joan",
10, "Cost, Distance , Family Friendly"], ["16204559-00", "Lisa-Marie",
5, "The facilities are fairly crowded which makes working out on
equipment or participating in classes cramped and difficult. "],
["16258576-00", "Michael", 7, "yhe cost way to much\r\n"],
["16161644-00", "April", 10, ""], ["1663157-00", "Mariela", 10, "Great
customer service, clean facilities and professional staff "],
["16114120-00", "Alison", 10, "The Y offers great programs and is
active in the local community. "], ["16177159-00", "Sheri", 10, "The Y
is a place for everything. It is a place for fitness, fellowship,
socialization, community, upward progretion of the youth, employment
opps..."]]
table([
["Member ID", "First Name", "NPS Score", "Comments"],
[member_id_and_first_name_and_nps_score_and_comments]
.transpose.reject{ |x| x[2].nil? }
],
:position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 45, 3 => 285}) do
row(0).style :background_color => 'C0C0C0'
end
The table is generating with only the header row (Member ID, First Name, etc.). The actual member_id_and_first_name_and_nps_score_and_comments array is not populating in the column.
Any thoughts as to why this is?
Try:
table([
["Member ID", "First Name", "NPS Score", "Comments"],
*member_id_and_first_name_and_nps_score_and_comments.reject{ |x| x[2].nil? }
],
:position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 45, 3 => 285}) do
row(0).style :background_color => 'C0C0C0'
end
I have the following code:
table([
["UnitID", "First Name", "NPS Score", "Comments"],
*[invite_unitid_arr, invite_name_arr, nps_score_integers_final, comment_arr]
.transpose.reject{ |x| x[3].empty? }
], :position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 60, 3 => 40, 4 => 150}) do
row(0).style :background_color => 'C0C0C0'
end
I am calling transpose on an array of arrays. I am refactoring this code and I now have an array of model objects:
array = Model.all
How can I rewrite the above, saying "Loop through each model (Model1, Model2, etc.) and create a row with the attributes unit_id,first_name,nps_score,comment like so: Model1[:unit_id],Model1[:first_name],Model1[:nps_score],Model1[:comment]"
If I understand correctly, you have an array of objects like this:
my_models = [ <MyModel id: 1, unit_id: 123, first_name: "Xxx", nps_score: 100, ...>,
<MyModel id: 2, unit_id: 456, first_name: "Yyy", nps_score: 200, ...>,
...
]
And you want an array like this:
[ [ "UnitID", "First Name", "NPS Score", "Comments" ],
[ 123, "Xxx", 100, "..." ],
[ 456, "Yyy", 200, "..." ],
...
]
All you really need to do is this:
headers = [ "UnitID", "First Name", "NPS Score", "Comments" ]
data = my_models.map do |model|
[ model.unit_id, model.first_name, model.nps_score, model.comments ]
end
rows = [ headers, *data ]
Or...
data = my_models.map do |model|
model.attributes.values_at(:unit_id, :first_name, :nps_score, :comments)
end
(Either way you could make this a one-liner, but mind your code's readability.)
Of course, it's always best to select only the columns you're going to use, so you could just do this (adding whatever where, order etc. calls you need):
my_models = MyModel.select([ :unit_id, :first_name, :nps_score, :comments ]).where(...)
data = my_models.map(&:attributes)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]
In Rails 4 the pluck method takes multiple arguments, making this even easier:
data = MyModel.where(...).pluck(:unit_id, :first_name, :nps_score, :comments)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]
I am not entirely sure what are you trying to achieve here, but it seems that you are looking for pluck method. Since rails 4 it allows you to pluck multiple columns at once (and by default will pluck all columns). So it seems that:
Model.pluck(:unit_id, :first_name, :nps_score, :comment)
Is what you are looking for - and is actually much better as it is not instantiating new objects and makes just one call to db. . It will return 2d array, one row for each model. If you rather prefer have different values of same column, add transpose on the above.
I'm using the following select helper:
f.select(:page_color, Orders::PAYMENT_TYPES ,:prompt => "Select a Box")
is it possible to change multiple columns with one selection? Say I want to change :page_color and :pay_method with the selection of "Check". Is this possible?
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
I think the cleanest thing would be to write a virtual attribute:
def paymethod=(value)
mapping = {
'check' => 'red',
'cc' => 'green',
...
}
self.page_color = mapping(value)
super
end