convert docx to pdf python linux

How to Convert DocX to Pdf in Python & Linux

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 & Linux. We will use docx2pdf library for this purpose.


How to Convert DocX to Pdf in Python & Linux

Here are the steps to convert docx to pdf files.


1. Install docx2pdf

Open terminal & run the following command to install docx2pdf

$ sudo pip install docx2pdf

On windows you can run the following command.

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

$ sudo docx2pdf /home/ubuntu/test.docx /home/ubuntu/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.

$ sudo docx2pdf /path/to/folder

Here is an example.

$ sudo docx2pdf /home/ubuntu/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.

$ sudo docx2pdf /home/ubuntu/data_files /home/ubuntu/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('/home/ubuntu/test.docx','/home/data/test.pdf')

#bulk conversion of files
convert('/home/user/data_files/')

If you are using the above library in Windows, you will need to use backslash in file paths.

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

Leave a Reply

Your email address will not be published. Required fields are marked *