Create PDF in background task

I have a feature where I need to generate a PDF using anvil.pdf.render_form in the background and then save it in the database. However, according to the documentation, it’s mentioned that “Background tasks cannot return Media objects directly.” Is there any workaround or alternative method to achieve this functionality in Anvil?

Background tasks can put data into data tables, that’s one way that they can pass media objects back to a caller.

2 Likes

Yes you are right. But I want to convert the anvil form into pdf using anvil.pdf.render_form in a background task. Is this possible in anvil?

Yes, and there are several Forum posts on this very topic. Many of them center on corner or edge cases (situations to watch out for), and how to deal with them.

Can you share any example project if available or links for this?

I don’t have any myself, but you are invited to use the forum’s Search feature. (The magnifying glass at the top of this web page.)

This can often get you answers much faster than waiting for a volunteer to reply.

1 Like

Not sure if you’ve landed upon a solution, i stuff .pdf files generated with the PDFRenderer into data tables routinely where the ‘file’ element of the data table is a Media Object. I also return (from the background task) the recid of that table element (I do this via the background task state), and then my front-end code ‘waiting’ for the background task to finish, can go fetch the .pdf and use media_download to render it to the browser. Hope this helps…

  if report_type == 100 or report_type == 300 or report_type > 500 or report_type == 201:
    report_file = PDFRenderer(quality='original', page_size=[22,28], margins={'top':.25,'bottom':.25,'left':.25,'right':.25},filename=fname).render_form('a1_BASE', pdfmtx, pages, report_type)   
   
  rec_dict = {'rfa_id': rfa_id,
             'create_datetime': datetime.datetime.now(),
             'file': report_file}
  
  record = app_tables.pdfs.add_row(**rec_dict)
  anvil.server.task_state['rec_id'] = record.get_id()

  retval = anvil.server.call('set_status', 'REPORT READY', rfa_id)
  anvil.server.task_state['status'] = prfx + ' Report Generation DONE!!!'  
1 Like