Search code examples
ruby-on-railsrubyruby-on-rails-4wicked-pdfwicked-gem

Wicked PDF: How to remove top margin from COVER page?


I'm generating pdf's from html using wicked_pdf. Right now, I want to remove top margin on the first/cover page .

This is a snipped code from my controller :

render :pdf => @project.name,
:javascript_delay => 1000,
:disable_external_links => false,
:encoding => 'UTF-8',
:cover => "#{root_url}/projects/#{params[:id]}/pdf_cover",     
:footer => {:html => { :template => 'projects/report_footer.pdf.haml' }, :spacing => 5},
:show_as_html                   => params[:debug].present?, 
:disable_smart_shrinking        => false,
:print_media_type => true,
:no_background => false,
:margin => { :top => 10, :bottom => 18 , :left => 0 , :right => 0}

enter image description here

As you can see above, in the controller action I set the top margin to 10 . So I'd like the top margin, the header and the footer to not be shown on the first page, but to be shown on the rest of the document pages. Attachments area


Solution

  • I see you also posted this on the Wicked PDF issue tracker

    The headers and footers and margins are global to the PDF created, so you can't tweak the cover page independently.

    However, you can create two PDFs, one of just the cover, and one of the rest and combine them with Ghostscript or PDFtk.

    Here's an example of how you might do that:

    html_content = render_to_string
    cover_pdf = WickedPdf.new.pdf_from_string(html_content, { footer: { margin: { bottom: 200 })
    body_pdf = WickedPdf.new.pdf_from_string(html_content, { footer: { margin: { bottom: 10 })
    
    cover_src_temp_file = Tempfile.new(['cover_src', '.pdf'])
    cover_src_temp_file.binmode
    cover_src_temp_file.write(cover_pdf)
    cover_src_temp_file.rewind
    cover_temp_file = Tempfile.new(cover_pdf)
    `pdftk #{cover_src_temp_file} cat 1 output #{cover_temp_file.path.to_s}` # first page only
    
    body_src_temp_file = Tempfile.new(['body_src', '.pdf'])
    body_src_temp_file.binmode
    body_src_temp_file.write(cover_pdf)
    body_src_temp_file.rewind
    body_temp_file = Tempfile.new(body_pdf)
    `pdftk #{body_src_temp_file.path} cat 2-end output #{body_temp_file.path}` # everything else
    
    output_temp_file = Tempfile.new(['output', '.pdf'])
    `pdftk #{cover_temp_file.path} #{body_temp_file.path} cat output #{output_temp_file.path}`
    send_file output_temp_file, disposition: 'inline'
    
    [cover_src_temp_file, body_src_temp_file, cover_temp_file, body_temp_file, output_temp_file].each do |tf|
    tf.close
    tf.unlink
    end