We all must have got requirement to generate PDFs at backend and store that on cloud. Well, here is a quick guide on how you can start generating the PDFs your own way without any limits.
Lets start generating PDF step by step:-
1: Add prawn gem to your Gemfile
1 | gem 'prawn' |
2: Create an instance of PDF document
1 | receipt_pdf = Prawn::Document.new |
3: Draw some text and style that in your own way
1 | receipt_pdf = Prawn::Document.new |
4: Adding a space/gap before and after drawing a text
1 | receipt_pdf = Prawn::Document.new |
5: Generate Output file
1 | # This will create a file at your project root directory |
Drawing tables:-
1: Prepare data to draw the table
1 | # Prepare receipt details to show in a table in the following format |
2: Add prawn/table requirement before drawing the table
1 | require 'prawn/table' |
3: Draw Table using prepared data
1 | receipt_pdf = Prawn::Document.new |
4: Styling Rows/Columns/Cells
1 | receipt_pdf = Prawn::Document.new |
Adding custom font to your PDF document
1: Download Font Files in .ttf format
2: Place them into font/your_font_name directory at project root level(Create one if it’s not there)
3: Set that font to your PDF document instance
1 | your_font = 'font/your_font_name/your_font_name.ttf' |
Limit the PDF page size to drawn area only OR Remove extra white area after drawing all your data
1: Set page length to much higher value than what you want to draw while creating instance on your PDF document
1 | receipt_pdf = Prawn::Document.new(page_size: [600, 2000], margin: 50) |
2: Do your drawing
1 | receipt_pdf.text 'My Drawing Here' |
3: Clip or Resize the document to the drawn area
1 | padding_after_drawing = 15 |
References:-
- Prawn Guide with examples
- Prawn Table Guide with examples