EzDevInfo.com

wicked_pdf

PDF generator (from HTML) plugin for Ruby on Rails

Adding metadata to PDF generated using Wicked PDF

I'm using Wicked PDF to generate a PDF from HTML. I've seen this SO question on adding metadata to a PDF, and it suggests using XMP metadata. How can I use Wicked PDF to add XMP metadata to a generated PDF?


Source: (StackOverflow)

wicked_pdf does not include styles

I used <%= wicked_pdf_stylesheet_link_tag "pdf" %> it shows the following output in the html

<link rel='nofollow' href="/stylesheets/pdf.css?1302860585" media="screen" rel="stylesheet" type="text/css"> <link rel='nofollow' href="file:///home/likewise-open/NEXTBRIDGE/nazar.hussain/osd/development/atlantis/public/stylesheets/pdf" media="screen" rel="stylesheet" type="text/css">

But when create the pdf it do not have any style. If i copy all css from the file to the header of the page, it includes all styles. What is the issue and how to solve it.


Source: (StackOverflow)

Advertisements

warning: already initialized constant PDF

Right now I am working on rails 3.0.0. If I run my project in terminal, I get this warning. Please help me.

/usr/share/ruby-rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.0/lib/action_dispatch/http/mime_type.rb:98: warning: already initialized constant PDF


Source: (StackOverflow)

Getting PDF from WickedPDF for attachment via Carrierwave

In Rails3, I am using the WickedPDF gem to render a PDF format of one of my models. This is working fine: /invoices/123 returns HTML, /invoices/123.pdf downloads a PDF.

In my Invoice model, I am using the state_machine gem to keep track of Invoice status. When an invoice goes from "unbilled" to "billed" state, I would like to grab a copy of the invoice PDF and attach it to the invoice model using CarrierWave.

I have the three parts working separately: the controller creates a PDF view, the model tracks state and triggers a callback when making the correct transition, and CarrierWave is set up properly. However, I'm having a heck of a time getting them to play nicely together.

If I just wanted to grab the HTML version of the invoice, I could call render_to_string from the model. But render_to_string seems to choke on receiving a PDF binary file. If I can get a stream of data back, it's pretty easy to write that data to a tempfile and attach it to the uploader, but I can't figure out how to get the data stream.

Any thoughts? Code below:

Invoice controller

def show
  @invoice = @agg_class.find(params[:id])

  respond_to do |format|
    format.pdf do
      render_pdf
    end
    format.html # show.html.erb
    format.json { render json: @aggregation }
  end
end

...

def render_pdf(options = {})
  options[:pdf] = pdf_filename
  options[:layout] = 'pdf.html'
  options[:page_size] = 'Letter'
  options[:wkhtmltopdf] = '/usr/local/bin/wkhtmltopdf'
  options[:margin] = {
    :top      => '0.5in',
    :bottom   => '1in',
    :left     => '0in',
    :right    => '0in'
  }
  options[:footer] = {
    :html => {
      :template   => 'aggregations/footer.pdf.haml',
      :layout     => false,
    }
  }
  options[:header] = {
    :html => {
      :template   => 'aggregations/header.pdf.haml',
      :layout     => false,
    }
  }
  render options
end

Invoice.rb

def create_pdf_copy

   # This does not work.    
   pdf_file = ApplicationController.new.render_to_string(
    :action => 'aggregations/show',
    :format => :pdf,
    :locals => { 
      :invoice => self
    }
  )

  # This part works fine if the above works.
  unless pdf_file.blank?
    self.uploads.clear
    self.uploads.create(:fileinfo => File.new(pdf_file), :job_id => self.job.id)
  end

end

UPDATE Found a solution.

def create_pdf_copy

    wicked = WickedPdf.new

    # Make a PDF in memory
    pdf_file = wicked.pdf_from_string( 
        ActionController::Base.new().render_to_string(
            :template   => 'aggregations/show.pdf.haml', 
            :layout     => 'layouts/pdf.html.haml',
            :locals     => { 
                :aggregation => self
            } 
        ),
        :pdf => "#{self.type}-#{self}",
        :layout => 'pdf.html',
        :page_size => 'Letter',
        :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
        :margin => {
            :top      => '0.5in',
            :bottom   => '1in',
            :left     => '0in',
            :right    => '0in'
        },
        :footer => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/footer.pdf.haml', 
                :layout => false
            })
        },
        :header => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/header.pdf.haml', 
                :layout => false
            })
        }
    )

    # Write it to tempfile
    tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

    # Attach that tempfile to the invoice
    unless pdf_file.blank?
        self.uploads.clear
        self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
        tempfile.unlink
    end

end

Source: (StackOverflow)

wicked_pdf_image_tag given undefined pathname for image

Hi i am using wicked_pdf for generating images after i save image when i generate pdf and used this tag for display image like this

  <%= wicked_pdf_image_tag(@image.snap.url(:original)) unless @image.blank? %>

it give me this unknown error

      ActionView::Template::Error (undefined method `pathname' for nil:NilClass):

while puts @image.inspect give me right path below

       "/system/snaps/7/original/flake.jpg"

Can any one help

Thanks....


Source: (StackOverflow)

problem implementing wicked pdf on heroku

I am using this guide for integrating wicked_pdf on heroku. But somehow it doesn't seem to work. I got the logs from heroku and its says this:

Processing PdfController#get_pdf to pdf (for 115.248.175.50 at 2011-02-15 23:54:44) [GET]
  Parameters: {"format"=>"pdf", "action"=>"get_pdf", "id"=>"1", "controller"=>"pdf"}
***************WICKED***************
Rendering pdf/get_pdf

RuntimeError (PDF could not be generated!
/usr/ruby1.8.7/lib/ruby/1.8/open3.rb:73:in `exec': No such file or directory - /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/bin/wkhtmltopdf-amd64       - -  (Errno::ENOENT)
    from /usr/ruby1.8.7/lib/ruby/1.8/open3.rb:73:in `popen3'
    from /usr/ruby1.8.7/lib/ruby/1.8/open3.rb:59:in `fork'
    from /usr/ruby1.8.7/lib/ruby/1.8/open3.rb:59:in `popen3'
    from /usr/ruby1.8.7/lib/ruby/1.8/open3.rb:57:in `fork'
    from /usr/ruby1.8.7/lib/ruby/1.8/open3.rb:57:in `popen3'
    from /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/vendor/plugins/wicked_pdf/lib/wicked_pdf.rb:22:in `pdf_from_string'
    from /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/vendor/plugins/wicked_pdf/lib/pdf_helper.rb:28:in `make_pdf'
    from /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/vendor/plugins/wicked_pdf/lib/pdf_helper.rb:39:in `make_and_send_pdf'
    from /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/vendor/plugins/wicked_pdf/lib/pdf_helper.rb:13:in `render'
    from /app/fa369291-829b-4b61-9efe-b2f0d0a0a42c/home/app/controllers/schedule_controller.rb:33:in `get_pdf'

Please Help. Thanks in Advance.

EDIT:

I made some changes in my code and got through this error but still stuck here

NoMethodError (undefined method empty? for #<Pathname:0x2b7112392480>)


Source: (StackOverflow)

Rails 3 -Render PDF from view and attach to email

I have been using Wicked_pdf to render a view as a PDF and actionmailer to send emails, but I can't get them to work together. I want to attach a PDF version of a certain view to an email using actionmailer and send it out by clicking a link or a button. I have a link_to command that sends out an email. Here is my controller that gets the email generated:

def sendemail
 @user = User.find(params[:id])
 Sendpdf.send_report(@user).deliver
 redirect_to user_path(@user)
 flash[:notice] = 'Email has been sent!'
end  

Here is what I have in my actionmailer:

class Sendpdf < ActionMailer::Base
default :from => "myemail@email.com"

def send_report(user)
@user = user
  attachment "application/pdf" do |a|
  a.body = #Something should go here, maybe WickedPDF.new.something?
  a.filename = 'MyPDF'
end     
mail(:to => user.email, :subject => "awesome pdf, check it")
end

end

I have seen many questions and answers, most dealing with Prawn. It seems like there should be a simple answer to this. Can anyone help?

UPDATE I'm grateful for a suggestion to use as an alternative option in the answer below. However, I would really like to learn how to render a view as a PDF and attach it to my email. I am open to using something different like Prawn or anything else if I need to.


Source: (StackOverflow)

Rails 3 ActionMailer and Wicked_PDF

I'm trying to generate emails with rendered PDF attachements using ActionMailer and wicked_pdf.

On my site, I'm using already both wicked_pdf and actionmailer separately. I can use wicked_pdf to serve up a pdf in the web app, and can use ActionMailer to send mail, but I'm having trouble attaching rendered pdf content to an ActionMailer (edited for content):

class UserMailer < ActionMailer::Base
  default :from => "webadmin@mydomain.com"

  def generate_pdf(invoice)
    render :pdf => "test.pdf",
     :template => 'invoices/show.pdf.erb',
     :layout => 'pdf.html'
  end

  def email_invoice(invoice)
    @invoice = invoice
    attachments["invoice.pdf"] = {:mime_type => 'application/pdf',
                                  :encoding => 'Base64',
                                  :content => generate_pdf(@invoice)}
    mail :subject => "Your Invoice", :to => invoice.customer.email
  end
end

Using Railscasts 206 (Action Mailer in Rails 3) as a guide, I can send email with my desired rich content, only if I don't try to add my rendered attachment.

If I try to add the attachment (as shown above), I get an attachement of what looks to be the right size, only the name of the attachment doesn't come across as expected, nor is it readable as a pdf. In addition to that, the content of my email is missing...

Does anyone have any experience using ActionMailer while rendering the PDF on the fly in Rails 3.0?

Thanks in advance! --Dan


Source: (StackOverflow)

wicked_pdf Error: PDF could not be generated

Gemfile

gem "wicked_pdf"
gem "wkhtmltopdf-binary"

the error:

RuntimeError in CarsController#show

Failed to execute:
/usr/bin/wkhtmltopdf     --print-media-type    -q - - 
Error: PDF could not be generated!
Rails.root: /u/apps/zeepauto/autozeep_update

cars_controller

def show
    @class_showcar = true
    @class_admin = true
    @car = Car.find(params[:id])
    @search = Car.search(params[:search])
    @cars_see_special = Car.where(:special => "1").order('rand()').limit(3)

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @car }
      format.pdf do
        render :pdf => "#{@car.carname.name}",
               :print_media_type => true
      end
    end
  end

show.html.erb

<p class="show_links"><%= link_to  url_for(request.params.merge(:format => :pdf)) do %>
  <%= image_tag('/images/printversion.png', :alt => 'Download') %>
</p>

wicked_pdf.erb

# config/initializers/wicked_pdf.rb
WickedPdf.config = {
#  :exe_path => '/var/lib/gems/1.8/bin/wkhtmltopdf'
  :exe_path => '/usr/bin/wkhtmltopdf'
}

Source: (StackOverflow)

Wicked PDF +fonts+heroku+rails3.2

I'm using wicked_pdf with rails 3.2.11 and ruby 1.9.3 to generate a PDF from HTML and deploying to Heroku.

My pdf.css.scss.erb:

<% app_fullhost = Constants["app_fullhost"] %>

@font-face {
  font-family:'DosisMedium'; font-style:normal; font-weight:500;
  src: url(<%=app_fullhost%>/app/font/dosis/Dosis-Medium.ttf) format('woff');
}

*, body {
  font-family: "DosisLight", 'Times New Roman', 'Arial', sans-serif;
} 

where app_fullhost is the exact host, in development or production.

My pdf layout includes among other things :

%html{:lang => I18n.locale}
  %head
    %meta{:charset => "utf-8"}
    %title= content_for?(:title) ? yield(:title) : Settings.app_name
    = wicked_pdf_stylesheet_link_tag "pdf"

In production.rb I have

config.assets.precompile +=%w(pdf.css)

This works without problems in development, but on Heroku the pdf file doesn't load the desired font. I have also tried different solutions like adding these in production.rb:

config.assets.paths << "#{Rails.root}/app/assets/fonts"
config.assets.precompile += %w(*.svg *.eot *.woff *.ttf) 
config.assets.precompile += %w(.svg .eot .woff .ttf) 

and I tried also to change ( in pdf.css.scss.erb ) :

@font-face {
  font-family:'Dosis'; font-style:normal; font-weight:500;
  src: url('Dosis-Medium.ttf') format('woff');
}

or

@font-face {
  font-family:'Dosis'; font-style:normal; font-weight:500;
  src: url(<%= asset_path('Dosis-Medium.ttf')%>) format('woff');
}

The fonts are in assets/fonts and also in public/app/font/dosis and url on Heroku respond correctly with:

..//myapp/app/font/dosis/Dosis-Medium.ttf" and 
..//myapp/assets/Dosis-Medium.ttf 

How can I get the font to load on Heroku?


Source: (StackOverflow)

Base64 @font-face Font with wicked_pdf Generator

I am trying to use a specific font in an HTML to PDF generated PDF file using wicked_pdf on a Rails 3 site. I have found other advice on here which I followed. The only thing that (mostly) worked for me was converting the fonts to base64. I found the original answer here: Wicked PDF +fonts+heroku+rails3.2

I had to put the @font-face CSS directly into the partial file that was using it instead of putting it into a style sheet in order for it to work. It works fine in my local copy now. When I deploy it to our staging server, it only half works. One of the fonts loads, but the bold version of the font does not load.

Here is the @font-face CSS I included in the partial (this pastebin includes the entire Base64 code in the off-chance that it's useful):

<style type="text/css">
  @font-face {
    font-family: 'MuseoSans300';
    src: url(data:font/truetype;charset=utf-8;base64,AAEAAAATAQAABAA...excess text removed);
  }
  @font-face {
    font-family:'MuseoSans700';
    src: url(data:font/truetype;charset=utf-8;base64,AAEAAAATAQAABAA...excess text removed);
  }
</style>

The styles from the regular style sheet (using SASS) which use these fonts look something like this:

#profile_pdf {
  font-family: 'MuseoSans300';
  h1 {
    font-size: 30px;
    font-family: 'MuseoSans700';
  }
  h2 {
    font-size: 20px;
    font-family: 'MuseoSans300';
  }
}

I've tried changing this a variety of ways. I used the same formatting as this advice: http://blog.shahariaazam.com/use-google-web-fonts-for-wkhtmltopdf-tools/#.UtwZUmQo5hE

That made it just stop working entirely.

With the formatting I showed above, it does work on my locally run copy. On the staging server only one of the fonts works; it loads everything in just the 300 version and the 700 version doesn't load. Has anyone else run into this problem?


Source: (StackOverflow)

wkhtmltopdf automatic page breaks

I'm using wkhtmltopdf v0.11.0 rc1 in a Rails application through wicked_pdf (I know wicked_pdf does not support the new command line parameter notation, I'm using my own fork of the gem). I thought that content not fitting within a page should automatically overflow to the next one, but this is not the case - I'm seeing text just being cut off, sometimes in the middle of a line.

I know I can layout my pages using page-break-after:always, but this looks like dirty hard-coding, and besides the HTML comes from an ERB template so it's not always obvious where to put page breaks.

Can something be done so that page breaks are inserted automatically? Am I missing something about how this works?

Here's what the generated command line looks like

\"c:/program files (x86)/wkhtmltopdf/wkhtmltopdf.exe\"
   --header-html \"file:///C:Users/bleak/AppData/Local/Temp/campaign_report.header.pdf_pdf_1580_0.html\" 
   --footer-html \"file:///C:/Users/bleak/AppData/Local/Temp/campaign_report.footer.pdf_pdf_1580_0.html\"
   --margin-top 20 --margin-bottom 15 --margin-left 5 --margin-right 40
   --page-size \"A4\"   
   page \"file:///C:/Users/bleak/AppData/Local/Temp/campaign_report_cover.pdf_pdf_1580_0.html\" --disable-javascript  
   toc --xsl-style-sheet \"c:/work/morizo/admoney/app/views/layouts/campaign_report.xsl\"  - - 

Source: (StackOverflow)

Uninitialized constant Mime::PDF using Wicked PDF gem / Rails 3 project

I'm getting this error when I try to submit my form (PDF is supposed to be generated using Wicked PDF gem, on form submission) -

NameError in PostsController#create

uninitialized constant Mime::PDF
Rails.root: /Users/fkhalid2008/littlechits

Application Trace | Framework Trace | Full Trace
app/controllers/posts_controller.rb:42:in `create'
app/controllers/posts_controller.rb:39:in `create'

How do I fix this??? Relevant code is below.

POSTS CONTROLLER

 def create
    @post = Post.new(params[:post])
    @post.user = current_user

    respond_to do |format|
        if verify_recaptcha && @post.save
            format.html { redirect_to :action=> "index"}
            format.pdf do
                render :pdf => "file_name"
                end
        else
            format.html { render :action => "new" }
            format.json { render :json => @post.errors, :status => :unprocessable_entity }
        end
    end
end

CONFIG/INITIALIZERS/WICKED_PDF.RB

# config/initializers/wicked_pdf.rb
WickedPdf.config = {
:exe_path => '/usr/local/bin/wkhtmltopdf'
}

Thanks,

Faisal


Source: (StackOverflow)

wicked_pdf: footer height/styling

I'm using the awesome wicked_pdf gem to generate a PDF, but I can't figure out how to change certain styles within the footer.

I'm having a HAML template for the footer looking roughly like this:

!!!
%html
  %head
    %meta{:charset => "utf-8"}
    = wicked_pdf_stylesheet_link_tag "pdf"

  %body
    .footer
      %p Line 1
      %p Line 2
      %p Line 3

And some styles:

.footer {
  padding-top: 1em;
  border-top: 1px solid #ccc;
}

The styles are applied just fine, but the due to a small height of the footer, only the first line is visible. I've tried to set the height via CSS, but no dice so far. If I set a footer using e.g the center, attributes or right supplying text directly, line breaks cause the footer to "grow" as expected.

Any idea on how to modify the footer height?


Source: (StackOverflow)

wicked_pdf + rails' asset pipeline + sass import in production

I'm successfully using wicked_pdf with SASS in development. I'm including a single .scss file, which contains several import rules for other .sass and .scss files, via this helper:

def wicked_pdf_stylesheet_link_tag(*sources)
  sources.collect { |source|
    "<style type='text/css'>#{Rails.application.assets.find_asset("#{source}.css").body}</style>"
  }.join("\n").gsub(/url\(['"](.+)['"]\)(.+)/,%[url("#{wicked_pdf_image_location("\\1")}")\\2]).html_safe
end

But switching to production the app still looks for the imported files which aren’t found.

I've added then a second manifest file to be pre–compiled in production.rb (config.assets.precompile += %w(pdf.css)) which contains a single require rule to pick up the mentioned .scss file. This file is compiled just fine but it seems that the helper doesn't pick up the right file in production and still looks to load the imported .sass files.

Has anyone experience how to solve this? The PDF creation requires absolute paths, which makes this task a bit more difficult.


Source: (StackOverflow)