Python script that exports data from an SQL DB (e.g. sqlite), runs it through a Word template and exports each result as PDF.
You can just use the provided sample employees.sqlite
or create your own:
- Create a DB
sqlite3 employees.db <<EOF
CREATE TABLE your_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
email TEXT
);
EOF
- Insert entries
sqlite3 employees.db <<EOF
INSERT INTO your_table (name, age, email) VALUES
('John Doe', 30, 'john.doe@example.com'),
('Jane Smith', 25, 'jane.smith@example.com'),
('Bob Johnson', 35, 'bob.johnson@example.com');
EOF
See template.docx
as an example.
To insert a (e.g.) name
field in the Word template:
Insert > Insert Field > Mail Merge > Merge Field > "MERGEFIELD name"
Tutorial and more details on using Mail Merge: https://pbpython.com/python-word-template.html
You can use the provided .venv
environment (for docx2pdf
or LibreOffice
), or create your own:
-
Python dependencies:
- create venv:
python3 -m venv .venv
- activate venv:
source .venv/bin/activate
- install dependencies:
pip install docx-mailmerge
- create venv:
-
Depending on the preferred pdf export option (see commented out code):
- docx2pdf (default)
- Depends on MS Word which must installed locally and licensed
- Produces optimum output (same as viewed in Word)
- Should work automatically for Windows (not tested)
- for Mac, due to security policies, requires initial access granting and then manual grant for each processed entry, making it unusable for large number of entries
pip install docx2pdf
- LibreOffice (commented out)
- Depends on LibreOffice which must be installed locally
- 100% free with good enough results (slight font differences)
- Runs automatically, no intervention needed. Not very fast (2-3 sec/entry).
- :
brew install --cask libreoffice
(Mac)
- Aspose (commented out)
- Paid solution ($1200 license required) in addition to MS Word on which it relies
- Without buying, produces unusable watermarks in the output
- Produces optimum ouput as well (same as viewed in Word)
- Works on Mac automatically as well, and very fast
pip install aspose-words
- Paid solution ($1200 license required) in addition to MS Word on which it relies
- docx2pdf (default)
- Ensure you've activated the venv:
source .venv/bin/activate
- Run the script:
python3 db-to-pdf-export.py
Output located in the output
folder (created at execution):
output/docx
- intermediary filled-in docx output, using the Word templateoutput/pdf
- final PDF output