Generating PDFs with Python (2023)

In Anvil, generating a PDF document is easy and we only need to use Python. Any Anvil Form can be made into a PDF with just a single function call! We can render an Anvil Form as a PDF by turning it into a Media Object. This means we can easily download our PDF, attach it to an email or store it in a Data Table.

In this tutorial, we’ll see how easy it is to generate, download and email PDF documents using Python in Anvil. We’ll build a simple web app where users can register for an event and download their ticket as a PDF. Follow along with the tutorial, or clone and try out the finished app:

Open in Anvil

Generating PDFs with Python (1)

If you’re completely new to Anvil, you may want to complete one of the ‘Start Here’ tutorials before beginning this tutorial.

Step 1 - Design your PDF

First, let’s design a Form that we want to convert to a PDF ticket. Add a new Blank Panel Form to the app and rename it ‘Ticket’.

We can design our Form however we like. To make the Form look like a ticket, I’ve added a Card with a dotted border and a Label that says ‘ADMIT ONE’. We should also add Labels to display the user’s name (name_label) and the date of the event (date_label):

Generating PDFs with Python (2)

We should change the __init__ of the Ticket Form so that it takes strings called name and date as arguments and displays them on the labels we just created. Switch to Code View in the Form Editor and change the __init__ function of our Ticket class so it looks something like this:

class Ticket(TicketTemplate): def __init__(self, name, date, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) self.name_label.text = name self.date_label.text = date
(Video) Create PDF with Python | Part 1

Step 2 - Create the user interface

Let’s now build a UI so that users can generate and download the ticket as a PDF. We’ll design a simple registration page for users to put in their name and email address and choose the date of the event they will attend.

Switch to Form1 in the App Browser. We need two TextBoxes so users can fill in their name and email address and two Labels for these. We’ll name the TextBoxes name_box and email_box. We’ll also need a DropDown named date_dropdown so that users can choose the date of the event.

We should populate the items property of our DropDown with a few dates. Each item in the DropDown should be on a separate line. We can also include a placeholder that says ‘choose date’.

Generating PDFs with Python (4)

Finally, let’s add a Button called register_button, so users can register and download their PDF ticket. Let’s add a click event for this Button that just displays our PDF form, so we can see what it will look like when it’s downloaded.

 def register_button_click(self, **event_args): """This method is called when the button is clicked""" name = self.name_box.text date = self.date_dropdown.selected_value open_form('Ticket', name, date)

Now, run the app! Fill in a name, select a date and click REGISTER to see with the ticket looks like.

Generating PDFs with Python (5)

Step 3 - Render and download the PDF

Our ticket is looking good! Now let’s turn it into a PDF. Rather than displaying the Ticket form in the browser, we’ll define a server function to render it as a PDF document.

We can only generate a PDF from Server code, so we’ll first need to add a Server Module to our app. We define a function which calls anvil.pdf.render_form(). This method returns a Media object, which means we can pass it back to the browser, download it or send it as an email attachment. We also need to decorate our fuction with @anvil.server.callable so we can call the function from client code.

Here’s what our server code looks like:

(Video) How to Generate an Analytics Report (pdf) in Python!

import anvil.pdf@anvil.server.callabledef create_pdf(name, date): pdf = anvil.pdf.render_form('Ticket', name, date) return pdf

Let’s call this function from the registration form then download the generated PDF. We use to call our server function and generate the PDF, and to save it. The click event should now look like this:

 def register_button_click(self, **event_args): """This method is called when the button is clicked""" name = self.name_box.text date = self.date_dropdown.selected_value pdf ='create_pdf', name, date)

That’s all we need to do to render a Form as a PDF. And we can download it with just one line of code!

Let’s test it out. Run the app again, fill in the form and click REGISTER. This time, the ticket will download.

Generating PDFs with Python (6)

Step 4 - Send your PDF as an email attachment

Once we’ve rendered our Form as a PDF, it’s easy to send an email with the document attached.

We first need to add the Email Service to our app. In the App Browser, click the + next to SERVICES and click on Email. To test out the app, we can check Test Mode so that all emails are redirected to us.

Generating PDFs with Python (7)

We can then write a function in the Server Module which calls create_pdf and then sends the rendered PDF as an email attachment:

@anvil.server.callabledef send_pdf_email(email, name, date): pdf = create_pdf(name, date) from_address='no-reply', from_name='Events', to=email, subject='Your Ticket', text='Thanks for registering!. Your ticket is attached to this email.', attachments=pdf ) return pdf
(Video) Generate PDF files with Python and ReportLab - #1 is available to all Anvil users, but on the Free Plan, emails will be redirected to the app owner. Email service is available on the Personal Plan and above, or by setting a custom SMTP server in the Email service.

Now let’s modify the register_button_click method in Form1 so that it calls the send_pdf_email function we just wrote. Since send_pdf_email returns the rendered PDF, we just need to swap it with create_pdf and pass in email:

 def register_button_click(self, **event_args): """This method is called when the button is clicked""" name = self.name_box.text date = self.date_dropdown.selected_value email = self.email_box.text pdf ='send_pdf_email', email, name, date)

We can now run the app again and our PDF ticket will be emailed to us. As long as we are in Test Mode, the ticket will always be emailed us no matter what email address we type in.

Step 5 - Check the input

We want to make sure that the user has actually filled in the registration form, so let’s add in a check before we generate the PDF ticket. We’ll alert the user if they haven’t filled the form, but if they have, we’ll tell them that their ticket will be downloaded and emailed to them:

 def register_button_click(self, **event_args): """This method is called when the button is clicked""" name = self.name_box.text email = self.email_box.text date = self.date_dropdown.selected_value if name and email and date: alert(f'Thanks for registering! Your ticket is downloading and will be sent to {email}.') pdf ='send_pdf_email', email, name, date) else: alert('You have not completed all required fields')

Try running the app again, but this time, leave at least one of the TextBoxes blank.

Generating PDFs with Python (8)
(Video) Create A PDF File With Python (Easy Way)

Step 6 - Optional: Set the PDF filename

Our app now generates, downloads and emails a PDF attachment when a user registers for our event. However, the PDF is called ‘print.pdf’ when we download it, which isn’t very descriptive. If we want to specify settings for our PDF document, we can use PDFRender(). Let’s modify our create_pdf function and specify a filename using PDFRenderer().

First add from anvil.pdf import PDFRenderer to the top of the Server code then modify the create_pdf function:

import anvil.pdffrom anvil.pdf import PDFRenderer@anvil.server.callabledef create_pdf(name, date): pdf = PDFRenderer(filename=f'{name} Ticket.pdf').render_form('Ticket', name, date) return pdf

Now when our ticket is downloaded, it will have a more useful name.

Step 7 - Run the finished app

We’ve now created a simple app which converts an Anvil form to a downloadable PDF and sends it as an email attachment. Let’s test out the finished app.

Generating PDFs with Python (9)

That’s it!

Your app is already live on the internet. Go to Publish App in the Gear Menu Generating PDFs with Python (10) for details.

You can check out the finished app here:

Open finished app

What’s Next?

Head to the Anvil Learning Centre for more tutorials, or head to our examples page to see how to build some complex apps in Anvil.

More tutorials

(Video) GENERATING PDFS WITH PYTHON - CS50 on Twitch, EP. 29


What is the best PDF library for Python? ›

The PDFQuery library is considered among the fastest Python scraping library. It acts as a light wrapper around pdfminer, pyquery, and lxml. It is designed in order to extract data reliably from sets of PDFs with as little code as possible.

How do I make an editable PDF in Python? ›

How to edit PDF
  1. Install PDF Editor for Python.
  2. Add a library reference (import the library) to your Python project.
  3. Open a PDF in Python.
  4. Insert content at the beginning of the PDF document.
  5. Call the 'save()' method, passing the name of the output file with the required extension.
  6. Get the edited result.

How do I automate a PDF? ›

Steps to automatically process incoming files: Open the PDF Converter Settings panel from Start > Programs > AssistMyTeam PDF Converter for Windows. Alternatively, invoke it from the context menu of Windows Explorer. From the Settings panel, go to Auto PDF tab and check 'Enable Automation' option.

Can Python create PDF report? ›

Creating PDF Reports with Plotly Graphs and Python. Since Plotly graphs can be embedded in HTML or exported as a static image, you can embed Plotly graphs in reports suited for print and for the web. This notebook is a primer on creating PDF reports with Python from HTML with Plotly graphs.

How do you create a PDF from data? ›

How to create PDF files:
  1. Open Acrobat and choose “Tools” > “Create PDF”.
  2. Select the file type you want to create a PDF from: single file, multiple files, scan, or other option.
  3. Click “Create” or “Next” depending on the file type.
  4. Follow the prompts to convert to PDF and save to your desired location.

Which programming language is best for PDF? ›

Being a high-level, interpreted language with a relatively easy syntax, Python is perfect even for those who don't have prior programming experience. Popular Python libraries are well integrated and provide the solution to handle unstructured data sources like Pdf and could be used to make it more sensible and useful.

What programming language does PDF use? ›

PostScript language

It can handle graphics and standard features of programming languages such as if statements and loop commands. PDF is largely based on PostScript but simplified to remove flow control features like these, while graphics commands equivalent to lineto remain.

Which Python is most useful? ›

There is a long list of Python packages designed for working with complex data sets. But arguably, Pandas is the most important. Pandas helps you manipulate and analyze large sets of data without having to learn a specialized data-processing language like R.

Can you automate PDF editing? ›

You can use the Action Wizard in Foxit PDF Editor to create an action that does all the work for you. Actions let you apply a sequence of commands to one or more files. There's no scripting required.

Does Python work with PDF? ›

You can work with a preexisting PDF in Python by using the PyPDF2 package. PyPDF2 is a pure-Python package that you can use for many different types of PDF operations. By the end of this article, you'll know how to do the following: Extract document information from a PDF in Python.

How do I make an entire PDF editable? ›

How to edit PDF files with Acrobat.
  1. Open your PDF file in Acrobat Pro.
  2. Click the Edit PDF tool on the right-hand panel. ...
  3. Use editing tools to add new text, edit text, or update fonts using selections from the Format drop-down list.
  4. Move, add, replace, or resize images using the tools in the Objects list.

What is PDF automation? ›

The Create PDF automation attaches a screenshot of a view to the case in PDF format. The view used must exist prior to configuring the automation. During execution, the view is rendered and the screen gets captured and converted to a PDF file.

How do I process a PDF form in power automated? ›

To extract tables from a PDF file, use the Extract tables from PDF action. In the action properties, specify the PDF file and the pages to extract from. The action produces a variable named ExtractedPDFTables that contains a list of PDF table info.

Can Adobe Acrobat be automated? ›

You can automate the use of Acrobat if the following three conditions are met: Acrobat application is installed on a client machine (Windows or macOS). Users must initiate automated tasks in Acrobat. For example, tasks that are run using the Acrobat Action wizard.

Can Jupyter notebook save as PDF? ›

The Jupyter Notebook has an option to export the notebook to many formats. It can be accessed by clicking File -> Download as -> PDF via LaTeX (or PDF via HTML - not visible in the screenshot).

Is Python good for reporting? ›

Besides data analysis, Python is also convenient for automating routine tasks such as reporting. Following this guide, you'll use tools with Python to generate reports, as the below common formats: Excel.

Can we convert Excel to PDF using Python? ›

Python developers can easily load & convert EXCEL files to PDF in just a few lines of code.
  • Load EXCEL file with an instance of Workbook.
  • Call the Workbook.Save method.
  • Pass output path with PDF extension as parameter.
  • Check specified path for resultant PDF file.

Should I generate PDF on frontend or backend? ›

If you want to generate a pdf with different templates then you need to go with front-end. If your template is the same, only the data inside it will be change then you should go with back-end.

How can I create a PDF for free? ›

Write on PDF files using a free PDF Editor

Go to the iLovePDF PDF Editor. Select the PDF file you want to edit or drag and drop it to start. In the top toolbar, choose from the writing tools, Text or Draw. You can freehand draw or type on the original PDF document.

Can we make PDF from drive? ›

Open your Google Docs file in Google Drive. From the File Menu, Click Download > PDF (this means Save as PDF). The download should start within a few seconds.

What is Elon Musk's favorite programming language? ›

Elon Musk's iconic company, Tesla, operates on an operating system built on the Python programming language. Elon Musk continues to prefer it as his favourite programming language. Elon Musk is a brand in himself.

Can you code a PDF? ›

Understand what you can code in PDFs

You can select and code text or regions of the page: 1 Select and code portions of text. By default, PDFs open in text selection mode—you can click and drag to select the text you want to code. You can also double-click to select a word and triple-click to select a line.

Which is the No 1 programming language? ›

JavaScript is the most common coding language in use today around the world. This is for a good reason: most web browsers utilize it and it's one of the easiest languages to learn. JavaScript requires almost no prior coding knowledge — once you start learning, you can practice and play with it immediately.

Can hackers use a PDF? ›

Yes, they can. Because PDFs are one of the most universally used file types, hackers and bad actors can find ways to use these normally harmless files — just like dot-com files, JPGs, Gmail, and Bitcoin — to create security threats via malicious code.

How long will it take to learn Python? ›

In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.

What are the 4 main uses of Python? ›

Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as accountants and scientists, for a variety of everyday tasks, like organizing finances.

Can you batch convert to PDF? ›

Luckily, you can batch convert files to PDF to save valuable time. Learn how to convert files to PDF in convenient batches with Adobe Acrobat or if you're on the move, with Acrobat online services. Both let you convert multiple document formats, from images to Word and Excel files.

Can edited PDF be detected? ›

If you go to the document properties of a PDF file (control or command d), if the proper metadata is available, it will list the creation date and time and modified date and time. This can help you determine if a pdf file has been modified since creation. However, it is not foolproof. This metadata is not secured.

Can Python scrape PDF? ›

With the help of python libraries, we can save time and money by automating this process of scraping data from PDF files and converting unstructured data into panel data.

Can you inject code into a PDF? ›

The same technique has been shown to also work within PDF files and is used to inject code and capture data. This is achieved by taking advantage of escape characters such as parentheses, which are commonly used to accept user input.

How do I create a PDF with node? ›

There are two major ways to approach creating a PDF file from Nodejs. The first way is to use a PDF generation library that uses straight JavaScript/Nodejs and everything is untemplated or the other way is to use something templated in a language like HTML and then generate the pdf from it.

What's the difference between PDF and PDF E? ›

PDF/X: Ensures the file will work when sent for professional printing (all fonts embedded, no RGB colors, etc.). PDF/A: Ensures the file is appropriate for archiving-that is, it will remain readable for a long time, despite changes in technology. PDF/E: Makes the file particularly useful for engineering documents.

Can any PDF be fillable? ›

Even then, not all PDF forms are editable documents. To fill these forms, convert them into editable PDF documents. In this article, we will tell you about the tools you can use to convert PDF into a fillable format.

How can I edit a PDF without Adobe? ›

Alternative method for editing PDFs in Word
  1. Open Microsoft Word and click the ''File'' option.
  2. Choose the ''Open'' option.
  3. Now, select the PDF file you want to edit.
  4. Here, you can see a notification that your PDF file is converted into an editable format.
  5. Click ''OK'' and you are ready to edit the file.

Can we automate PDF using selenium? ›

Selenium does not have any inbuilt functionality to test the content of PDF files; hence it needs to use the third-party library Apache PDFBox. It is an open-source Java tool and can be used with Selenium Java and TestNG to assert the content of PDF.

Can a PDF animate? ›

Very few people are aware that Adobe's PDF files actually support movement and multimedia! Yes, you can have animations and transitions within PDFs, and also these PDFs can contain audio and video files.

Is PDF the same as AI? ›

(1) In the general case, PDF files are not Adobe Illustrator files and vice versa. If you choose Illustrator 8 or earlier, you end up with a file that looks like, but isn't, an EPS file. That format doesn't support live transparency, color management, etc.

Is Power Automate free? ›

Free plan. If you sign in with work or school email address, you get all Power Automate capabilities included in Office 365. But if you have a non-business user account (such as an account that ends with or, you can still use Power Automate with the free plan.

Is Adobe API free? ›

Adobe PDF Embed API

Standardize your end-user viewing experiences with interactivity and analytics, all at no charge! Unlimited access at no charge.

What is better than Adobe Acrobat? ›

Foxit is a powerful alternative to Adobe Acrobat. It is available for all Operating Systems including iOS and Android mobiles. It allows you to edit a PDF, along with sharing it and commenting on it. There are many other features that you can use that make it a worthy alternative.

Is Adobe Acrobat being discontinued? ›

Adobe Acrobat Pro XI and Adobe CS6 will be discontinued at UA on May 9, 2022.

How do you create an empty file in Python? ›

Creating an empty Text file
  1. Use "w" to open a file for writing. If the file doesn't already exist, the open() method is used to create it. ...
  2. Pressing "x" will allow you to open a file for an exclusive creation. If the file is present, the open() function raises an error.
17 Aug 2022

How do you make a blank in Python? ›

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

How do you empty a file in Python? ›

By passing a value of 0 to the truncate() method, it's possible to clear the text file completely. The above Python code will clear a text file of it's content. Using the truncate() method in this manner will reduce the file size to 0, erasing any content the file contained.

Does Python open create file? ›

Create A Empty Text File

We can create a file using the built-in function open() . Pass the file name and access mode to the open() function to create a file. Access mode specifies the purpose of opening a file. Below is the list of access modes for creating an a file.

How do you create a file and write it in Python? ›

How to Create a Text File in Python
  1. Step 1) Open the .txt file f= open("guru99.txt","w+") ...
  2. Step 2) Enter data into the file for i in range(10): f.write("This is line %d\r\n" % (i+1)) ...
  3. Step 3) Close the file instance f.close() ...
  4. Step 1) f=open("guru99.txt", "a+")
5 Nov 2022

How do you create a file without opening it in Python? ›

Of course there IS a way to create files without opening. It's as easy as calling os. mknod("newfile. txt") .

Can you create a CSV file in Python? ›

In Python, you can use the CSV writer's writerows() function to write multiple rows into a CSV file on the same go. Example. Let's say you want to write more than one line of data into your CSV file. For instance, you may have a list of students instead of only having one of them.

What does empty print () do in Python? ›

What does blank print () do in Python? It prints an empty line, just as you have said. It will leave a blank line in the output. The print statement prints its arguments, and then a newline, so this prints just a newline.

Why do we use empty string in Python? ›

It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.

How can I blank a PDF for free? ›

How to black out text in a PDF file.
  1. Open your PDF in Adobe's Acrobat online services.
  2. Select Tools, then Redact.
  3. Select text. Either double-click to select the text or drag to select lines of text.
  4. Apply redaction. Once you've selected the text you want to remove, click Save to apply the changes and save the document.

Can a PDF be fillable? ›

In Adobe Acrobat you can make a PDF fillable form from scratch, convert PDF files from a Microsoft Word document, or even upload a smartphone image or a scanned paper document.

How do I edit a PDF? ›

How to edit PDF files:
  1. Open a file in Acrobat.
  2. Click on the “Edit PDF” tool in the right pane.
  3. Use Acrobat editing tools: Add new text, edit text, or update fonts using selections from the Format list. ...
  4. Save your edited PDF: Name your file and click the “Save” button.

What is A+ mode in Python? ›

The a+ mode opens the file for both reading and appending. The file pointer in this mode is placed at the end of the file if it already exists in the system. The file opens in the append mode. If the file does not exist, then it is created for writing.

How do you create multiple files in Python? ›

How do you write two files in Python?
  1. Open file1. txt and file2. txt in read mode.
  2. Open file3. txt in write mode.
  3. Read the data from file1 and add it in a string.
  4. Read the data from file2 and concatenate the data of this file to the previous string.
  5. Write the data from string to file3.
  6. Close all the files.

How do I write a Python program in idle? ›

Clicking on IDLE will open up the Python shell. You can either start writing your code here or hit control + N and open up a new file. Write your code in this file and save it. IDLE automatically saves all the files either with .


1. Working With PDF Files In Python: Creating a PDF, Extracting Text, and Converting Files
(Rishab Teaches Tech)
2. Create PDF Tables with Python FPDF2
(Chart Explorers)
3. How to Create PDF Files with Python [New Method 2022] || Making an Invoice PDF
(Frank Andrade)
4. How to generate Reports with Python automatically - 4: PDF directly
(Lianne and Justin)
5. How to Create PDFs with Python and Reportlab
(Shane Lee)
6. Generating Dynamic PDFs With Flask
(Pretty Printed)
Top Articles
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated: 01/14/2023

Views: 6185

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.