Sometimes you may need to convert docx files to pdfs. In this article, we will look at how to convert docx to pdf using Python. We will use docx2pdf library for this purpose.
How to Convert DocX to Pdf in Python
Here are the steps to convert docx to pdf files. Please note, Docx2pdf is available only in Windows. It is not supported in Linux. In such cases, it is better to use an online docx to pdf convertor like SmallPDF.
1. Install docx2pdf
Open command prompt & run the following command to install docx2pdf
C:\> pip install docx2pdf
2. Convert Docx to Pdf using command line
Here’s the syntax of docx2pdf
docx2pdf [input] [output]
In the above command, you need to specify the file path of docx file as first argument and the file path of pdf file to written as second argument.
Here’s an example to convert docx to pdf
C:\> docx2pdf C:\Project\test.docx C:\Project\test.pdf
We have mentioned absolute paths for both input and outpur files. If you don’t mention absolute paths above, then docx2pdf will look for docx files as well as write pdf files in your present working directory.
3. Bulk Conversion using command line
You can also bulk convert a folder of docx to pdf files by specifying the folder path as input.
C:\> docx2pdf /path/to/folder
Here is an example.
C:\> docx2pdf C:\Project\data_files
In the above command, docx2pdf will convert all docx files present in /home/ubuntu/data_files into pdf files.
You may also specify different input and output paths in docx2pdf command.
C:\> docx2pdf C:\Project\data_files C:\Project\test_files
4. Docx to PDF conversion from program
You may also import docx2pdf library within python program and use convert function to convert docx to pdf files.
using docx2pdf import convert #convert a single docx file to pdf file in same directory convert(test.docx) #convert docx to pdf specifying input & output paths convert('C:\Project\test.docx','C:\Project\test.pdf') #bulk conversion of files convert('C:\Project\')
As you can see it is very easy to convert docx to pdf files in python.
Also read:
How to Setup SSH Passwordless Login
How to Change NGINX User
How to Remove URL Parameters using .htaccess
How to Set Apache PATH Environment Variable
How to Export to CSV in NodeJS
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.