Hello my gorgeous friends !!!
In this article i am going to show you what I did in order to achieve following tasks.
- Generate PDF Content
- Handle the PDF generation as a background job
- Make the link available in an email for the download purpose
Alright then, Let’s start.
Generate the content as a PDF
For this section I have used the following Gem out of many libraries which does the same thing.
If you wanna take look at inside this library here is the link.
This awesome library makes the PDF generation easy. These are the steps I followed.
- Add the Gem into the file and install it.
2. Change the require method with respond_to block.
for this I had to create a separate template for the PDF generation and it referenced in
html = render_to_string template: "PDF template file"
I have added those files in a folder named “PDF” under the view directory like this.
Wicked PDF library generates the PDF from the HTML string. So we can parse the string into the wicked pdf library like this.
pdf = WickedPdf.new.pdf_from_string(html)
html refer to the string we render from the template. look above :)
That’s all here. But these is a little problem when this string a huge. It’ll hold the server until it completes the PDF generation. Therefore I needed to make this process in the background. So it’ll generate the PDF without interrupting the main thread.
Handle the PDF generation as a background job
For this we can easily use the Rails Active Job facility. We can first create a class to perform this operation.
To create a new job
rails generate job pdfs_generate
those jobs will be saved in a new folder named as “Jobs”
For the Job execution we need a queuing library. There are many such libraries. Some examples are bellow.
Here I am using “Delayed Job”
Now. It’s time to embed the wicked PDF generation process inside the Job class.
There are two main things in a JOB.
1. Perform method
2. Call backs → after_perform, before_perform, etc.
Perform method will do the process in background and once it is completed it will call the callback method named as “after_perform”. And I used that method to send the email after the PDF generation process.
Here is my PDF generate Job class file.
In order to call the Job process I changed my show method by getting the perform function in a new thread and call the perform function using the later postfix.
In here, Wicked PDF generation will happen in a new thread and in the background so, this will not affect the main rails process. So we can give a availability to the user to do any other work. rails generate job guests_cleanup
According to my code once the PDF work is finished it will send the email to the current user email as I described above. (remind → after_perform callback)
This What I did to finish the task “PDF generation in background”