If you've ever done any sort of development work for a company of any size, you know that almost all companies send and receive information in more or less the same way: via PDF files.
Whether you're sending out newsletters or invoices, they're all delivered in PDF format, and just about every personal computing device on the planet has a PDF reader installed on it to be able to access these files.
For businesses, the ability to dynamically generate invoices based on sales data extracted from a database eliminates the rush to dispatch all invoices at the end of the month. Alternatively, a template-type PDF can be filled in with accurate information for specific users who've indicated that they're only interested in receiving newsletters for certain categories, like monthly specials.
In this article, you'll learn all about generating PDFs in a Python, a versatile scripting language. You'll be introduced to two popular PDF generation libraries for Python and learn how to leverage these libraries to generate your own PDF files. Additionally, you'll explore Dropbox Sign, an API that can be used to digitally sign PDF files using legally binding eSignatures.
Methods to generate a PDF in Python
Before you review specific tools/libraries for generating a PDF in Python, you need to prepare a Python project.
Set up a virtual environment
It's good practice to set up your Python project using virtual environments. While it's possible to run your Python script under the global Python interpreter, your global environment can end up cluttered if you keep installing packages that your project needs under the global system packages.
Additionally, if you package your virtual environment with your project, you can ensure that the installation process is smooth when you want to use the same project on another system.
When you upload your project to a code-sharing platform site like GitHub, it also simplifies virtual environment setup for other users who want to clone your project on their local systems.
There are all kinds of ways to set up a virtual environment. This tutorial uses an advanced package tool (APT)–based package manager, which means it may differ from your system. So adjust your commands accordingly.
The commands used in this tutorial are all run inside a terminal window on a Linux-based computer. Run the following commands:
Finally, activate your virtual environment using the newly supplied shell script:
You should see that your prompt gets modified to show you that you're working inside a virtual environment for your Python project:
You can deactivate the virtual environment by entering deactivate
:
If you want to install any project-specific modules, you should do so while your project's virtual environment is activated. This ensures that the module is only available to your project and not the global Python interpreter.
From here, you can also set up a Git repository for your project if that's how you normally do things, but this step is beyond the scope of this tutorial.
Now, it's time to create your first PDF using ReportLab.
Use ReportLab to create a PDF
ReportLab is a PDF library that lets you create PDF files using the Python language.
To include the ReportLab module in your project, remember to activate your virtual environment and run the following:
And that's it! That's all you need to do to include the module as part of your Python project.
Create a PDF with ReportLab
To create a PDF, start with a skeleton for your main script:
This program will run as is, but it doesn't do anything except output "nothing to do! (yet)"
to the console.
It's time to start modifying the code so that you can create a PDF file. ReportLab supports multiple methods for creating a PDF file, but you can start by using the Canvas
class:
Once you've run this code, you should have a hello_world.pdf
file waiting for you in your project directory. Open it up, and you should see something like this:
![ReportLab PDF first run](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdc3_66609404ae654b127334ed84_O9P1tzz.png)
As you can see, it worked! Now, it's time to expand the code and see what other options are available.
Draw shapes with ReportLab
Once you've created your PDF, you can modify your code to draw shapes using the ReportLab library. The following code is the entire main.py
with all the necessary changes you need to draw some shapes on your canvas object:
This code draws a few shapes onto the canvas before saving it as a PDF:
![RepotLab PDF with shapes](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdc0_6660945165492c0f8231a0a0_fxr0hKa.png)
Change fonts with ReportLab
Next, try changing the font of your string. For this, you're going to need a fonts
directory in the root of your project path, and you'll need to drop a TrueType Font file (TTF) in that directory. There are plenty of free and open source TrueType fonts on the internet, and you can try any that you like. Here, Inter is used.
Once you've downloaded a font and extracted the TTF file to the fonts
directory, take a look at the following code:
Look carefully at these lines:
Make sure to set these values according to the font file you downloaded and extracted to the fonts
directory.
Run the script to confirm that the font has changed:
![ReportLab PDF third run](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdc6_6660949e4046070a4bb34108_gX2brgk.png)
Other things to try with ReportLab
ReportLab has a lot more features available. If you're interested in learning more, check out their documentation to find out more about features such as the following:
ReportLab also has a ReportLab PLUS library, which is a paid library that supports creating PDF files using a templating language called Report Markup Language (RML). This allows you to create PDF files using a structure similar to HTML.
The code for this example project is available on GitHub.
PDFKit
PDFKit is another popular Python package that can generate PDF files. However, it has a different methodology when it comes to creating PDFs. Instead of manipulating a blank canvas, it allows you to take standard HTML pages and convert them to PDF.
This approach works wonderfully for developers who might already be well versed in HTML, while others might find the clean slate approach that ReportLab offers more appealing.
Follow the same instructions for preparing a Python project as before but in a separate directory and virtual environment. Additionally, create the same skeleton script as was used previously.
Then install PDFKit into your activated virtual environment using the following command:
PDFKit also requires the wkhtmltopdf
binary to be installed on the system.
On an APT-based system, install it like this:
If you're struggling to install it on your system, please consult the wkhtmltopdf documentation to try to resolve your issue.
Use PDFKit to create a PDF
There are multiple ways you can generate a PDF using PDFKit. You can even generate a PDF from an existing URL. However, for this tutorial, you're going to create your own HTML file.
A common business use-case might be something like a Non-disclosure agreement or an NDA. The basic HTML file looks like this:
Name this file contract.html
and place it in the root of your project.
Then modify the skeleton script to look like this:
Once you run this code, you should have a PDF file in the root of your project directory that looks like this:
![PDFKit first run](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdcc_666095319e5606973c8a8033_Cj6h9b3.png)
Add options with PDFKit
You can pass an options
object to the main method to set parameters like margin
and page size
to make sure the HTML fits nicely on the page. To do so, modify the main()
method like this:
For a list of the options that you can set, consult the documentation.
Add color with PDFKit
Currently, the contract looks a bit bland, but just like with normal HTML, it's something you can remedy using CSS.
Create a basic CSS file that changes the color of the <H1>
heading and changes the icon of the bulleted list:
Save this file as style.css
in the root of your project directory.
Now modify the following line in main.py
to use your newly created CSS file:
Run the command again to see what your new contract looks like:
![Add color with PDFKit](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdf1_6660960d80df897dc007c9ed_TnjQUbx.png)
As you can see, PDFKit is fairly flexible if you're familiar with HTML and CSS. Anything you can dream up in HTML can be converted to a PDF file.
All the code examples for this project are available in this GitHub repository.
Dropbox Sign
Dropbox Sign is a service from Dropbox that allows you to digitally sign your PDF files. It helps you streamline any business workflow that might require a signature on the customer's end.
This removes the hassle that most customers experience when they need to physically sign a form, like having to print, sign, and finally, scan the document in order to send it back. Additionally, the signatures are considered to be legally binding signatures.
In this section, you’ll explore a common use case for using a service like Dropbox Sign.
You've been tasked by your employer, “The Company”, to streamline the sending of NDAs to prospective third-party developers who might be on-boarded from time to time as needed.
Sign up for the Dropbox Sign API
If you're a Dropbox customer already, you can skip this step. If not, you'll need to sign up for a Dropbox account.
Once you've selected which account you want to sign up with, you need to accept the terms and conditions:
![Dropbox Sign Terms and Conditions](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdcf_666096e78b4fbb1f28204937_Adci2hL.png)
Depending on your needs, you'll be asked which plan you want to sign up for. If you're only testing the service for possible future use, you can select the Start free trial button on any of the plans:
![Dropbox Sign plan selection](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdc9_6660974b0dce3674c805620b_w2vmq19.png)
Even if you're only using the free trial, you still need to provide your credit card details. Don't worry, as long as you cancel before the trial period is up, you won't be charged:
![Dropbox Sign credit card details](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdd2_66614ea2a7cc81d396c790bc_DzMxjkA.png)
Note that there are differences in what you can do with the API depending on which plan you sign up for:
![Dropbox API restrictions based on plan](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be2b_66614ef82c04b6217640bc78_h4Cadwn.png)
Once you've signed up, you'll be logged into the main application page:
![Dropbox Sign Application page](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be18_66614f2e34e4f8ed63491703_7VFjLwH.png)
Prepare your first document template with Dropbox
To prepare your first document template, click the Create a template button on the home page to get started.
While you can use any PDF, this tutorial will use the contract.pdf
file that was created in the previous example. Upload that file to the template and click Next:
![Dropbox Sign document template creation](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bddd_66614fae1fb1848e1a16bb28_OBIrQIB.png)
Next, you'll need to create a signer role. In this example, call the role Developer and click Next:
![Dropbox Sign role creation](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdf7_66614ff20158f68af650c0e9_BZqNXQ1.png)
You should be greeted by the template designer, where you can add all sorts of fields to your PDF file:
![Dropbox Sign template designer](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be0f_6661502a672ec8b411d66248_Z903HOk.png)
Some fields can be automatically filled when a signature request gets generated. The “Date Signed” field is a good spot to do this. Drag a “Date signed” field from the “Auto-fill fields” section on the left to the location on the PDF where you would like the date to appear:
![Add Date Signed field](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be12_66615058600b0bc91a63cf24_aSRKBm7.png)
Next, drag a “Signature” field from the left sidebar to the position where you would like it to appear on the template:
![Dropbox Sign signature field](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be23_66615081ea898a2fae6e7bf6_P9PRSfo.png)
With the field selected, check the right sidebar for field options and make sure the field is set to Required and the right signer role has been selected. Also, note the field name, as you will need to reference that name in your Python code later:
![Dropbox Sign signature field details](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdfd_666150c71fb1848e1a177cb1_Imgur.png)
Once completed, click Next.
Review, give your template a name, and save it:
![Dropbox Sign save template](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdd5_6661510b04b39bc9043a7678_eP8EngS.png)
Now, you're ready to integrate this into your Python workflow to send a signature request to your friend.
Create an API key
For your Python project to authenticate to the Dropbox Sign API, you need to create an API key.
Navigate to the Settings page and then click API:
![Dropbox Sign API settings](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be05_6661666872373216c6bbe330_Es4HXSn.png)
Click Generate Key and give your API key a name:
![Dropbox Sign API key generation](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdee_666166b7129c73fb0eb66f91_4IeqrfZ.png)
Lastly, copy the key by clicking the copy icon on the newly generated key:
![Dropbox Sign API copy key](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdd8_666166fa3113e417b1ad4717_5DaP2cS.png)
Prepare your project
Prepare your Python project in the usual manner:
- Create a project directory.
- Create a virtual environment in that directory using
python3 -m venv .venv
. - Create a
main.py
file with the normal bare-bones skeleton. - Create an empty
config.py
file that will store your API credentials.
Finally, don't forget to install the Dropbox API module in your virtual environment:
Set up API access
To set up API access, you need to fill out the script with the basics:
And config.py
should look like this:
Once you run that, you should get an output that gives you a few statistics regarding your account:
This means you've successfully connected your Python script to the API.
Next, you'll want to send the template you created previously to your friend for signing. To do so, modify the main script like this:
You'll notice that your data
object requires a value for the template_ids
variable. You'll need to fetch the template ID for the document template you created.
Navigate to the Templates page and view the information for the template you created:
![Dropbox Sign templates View info button](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be09_66616850b2859a62299cdd80_2aTzdp1.png)
![Dropbox Sign get Template ID](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bde0_66616889cca5cea937ef6466_UtyW81e.png)
Modify config.py
to include the Template ID:
Replace all the placeholder values in config.py
with the correct ones. Notice that TEMPLATE_IDS
is a Python list because the signature_request_send_with_template
method supports sending multiple document templates with a single request.
Also, note that your data
object has test_mode
set to True
. While test_mode
is True
, the documents are not considered legally binding. This is a good setting to have while you are in a testing phase. For the production code, you would need to set that to False
.
Now, run your code.
If all goes well, you should receive a response like this:
Success! The rockstar developer you found on LinkedIn should have the contract waiting in their inbox, ready to be signed.
Sign the document
The email that the prospective developer receives will look like this:
![Dropbox Sign signature request](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdfa_66616a2bd1cd9dd4f17e6ca5_6pnZGQm.png)
Once your friend clicks the Review & sign button, they'll be taken to a page where they can sign the document.
The signature field looks like this:
![Dropbox Sign signature request field](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be15_66616a684a75b72238412133_mmrA5Hy.png)
Clicking on that field gives you the signature widget, where you can digitally sign the document:
![Dropbox Sign signature widget](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be20_66616aa9f0f20edecabf3e98_EfbFDyh.png)
Once you click Insert, the signature will be embedded in the document.
The prospective developer can now click Continue in the top right-hand corner, review the Dropbox Terms of Service, and then click I agree.
Once the signature has been submitted, the signer will be greeted by the last page:
![Dropbox Sign successful signature](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3bdf4_66616b141daa0327100cb6e7_XzrCE8O.png)
Confirm the signed document
On your Dropbox Sign home page, navigate to the Documents tab on the left sidebar. You should find a signed copy of the contract here:
![Dropbox Sign signed copy of the contract](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be0c_66616b6e63b0af6add3313d1_3CrGJlg.png)
Download the PDF to see your (soon-to-onboarded) developer’s signature on the document:
![Signed PDF](https://cdn.prod.website-files.com/6446df33610093270e7fb677/66b3946be743866b21f3be2e_66616b99cc40e38d99a71ace_xheoOb8.png)
And you're done!
All the code used for this example is available in this GitHub repository.
Conclusion
In this tutorial, you learned how to do the following:
- Create PDF files from scratch using ReportLab
- Convert HTML files to PDF files using PDFKit
- Create an entire workflow from start to finish using the Dropbox Sign Python SDK
And that's only scratching the surface of what's possible with these tools. You could streamline all kinds of business processes including accepting quotes and estimates, signing contracts, and signing school permission slips.
If you're planning on using PDFs in your business processes, Dropbox Sign could be the perfect automation tool to save you time and effort.
ได้รับข้อมูลเสมอ
Thank you!
Thank you for subscribing!