Convert Word file to PDF, HTML and PDF to JPG, PNG in Python

Convert Word file to PDF, HTML and PDF to JPG, PNG in Python

In this blog, we will convert a word file to pdf and html. Also we will convert pdf to jpg and png file. We will use docx2pdf, mammoth, pdf2image Python modules for conversion.

We have sample.docx file, which we are going to use for this blog. Content in word file:

What is docx2pdf?

Convert docx to pdf on Windows or macOS directly using Microsoft Word (must be installed).

Install the docx2pdf module via pip

pip install docx2pdf

Python module is installed. Open Jupyter notebook and import module.

View word files in current directory

In [1]:
!dir *.doc *.docx
 Volume in drive E is projects
 Volume Serial Number is 6AEC-D309

 Directory of E:\jupyter-notebook-workspace


 Directory of E:\jupyter-notebook-workspace

05/20/2022  02:19 PM            14,088 sample.docx
               1 File(s)         14,088 bytes
               0 Dir(s)  207,434,731,520 bytes free

We have sample.docx file in current directory.

Import mdule

In [2]:
from docx2pdf import convert

Convert word file into pdf

In [3]:
folderDir = "E:/jupyter-notebook-workspace/"
In [4]:
inputFile = folderDir + "sample.docx"
outputFile = folderDir + "sample.pdf"
In [5]:
convert(inputFile, outputFile)
  0%|          | 0/1 [00:00<?, ?it/s]

View word file after creating

In [6]:
!dir *.pdf
 Volume in drive E is projects
 Volume Serial Number is 6AEC-D309

 Directory of E:\jupyter-notebook-workspace

05/21/2022  07:11 PM            82,877 sample.pdf
               1 File(s)         82,877 bytes
               0 Dir(s)  207,434,731,520 bytes free

Convert word file in html file

What is mammoth?

Convert Word documents from docx to simple and clean HTML and Markdown.

Mammoth is designed to convert .docx documents, such as those created by Microsoft Word, Google Docs and LibreOffice, and convert them to HTML. Mammoth aims to produce simple and clean HTML by using semantic information in the document, and ignoring other details. For instance, Mammoth converts any paragraph with the style Heading 1 to h1 elements, rather than attempting to exactly copy the styling (font, text size, colour, etc.) of the heading.

Install mammoth via pip

pip install mammoth

Import module

In [7]:
import mammoth

Convert docx into html

In [8]:
with open(inputFile, "rb") as docx_file:
    result = mammoth.convert_to_html(docx_file)
    html = result.value # The generated HTML
    messages = result.messages
In [9]:
html
Out[9]:
'<p>Alice’s Adventures in Wonderland</p><h1>Down the Rabbit-Hole</h1><p>Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice “without pictures or conversations?”</p><p>So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.</p><p>There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, “Oh dear! Oh dear! I shall be late!” (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.</p><p>In another moment down went Alice after it, never once considering how in the world she was to get out again.</p><p>The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.</p><p>Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled “ORANGE MARMALADE”, but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.</p>'

Save html into file

In [10]:
f = open(folderDir + 'sample.html',"w")
f.write(html)
f.close()

We have saved file in sample.html. Let us view the sample.html.

Convert pdf to image

What is pdf2image?

A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.

Windows users will have to build or download poppler for Windows. I recommend @oschwartz10612 version which is the most up-to-date. You will then have to add the bin/ folder to PATH or use poppler_path = r"C:\path\to\poppler-xx\bin" as an argument in convert_from_path.

Mac

Mac users will have to install poppler for Mac.

Linux

Most distros ship with pdftoppm and pdftocairo. If they are not installed, refer to your package manager to install poppler-utils

Platform-independant (Using conda)

Install poppler: conda install -c conda-forge poppler
Install pdf2image: pip install pdf2image

Install pdf2image and poppler module

pip install pdf2image

conda install -c conda-forge poppler

Import module

In [11]:
from pdf2image import convert_from_path

convert_from_path(pdf_path, dpi=200, output_folder=None, first_page=None, last_page=None, fmt='ppm', jpegopt=None, thread_count=1, userpw=None, use_cropbox=False, strict=False, transparent=False, single_file=False, output_file=<pdf2image.generators.ThreadSafeGenerator object at 0x000002488FC544F0>, poppler_path=None, grayscale=False, size=None, paths_only=False, use_pdftocairo=False, timeout=None, hide_annotations=False)

Description: Convert PDF to Image will throw whenever one of the condition is reached
Parameters:
    pdf_path -> Path to the PDF that you want to convert
    dpi -> Image quality in DPI (default 200)
    output_folder -> Write the resulting images to a folder (instead of directly in memory)
    first_page -> First page to process
    last_page -> Last page to process before stopping
    fmt -> Output image format
    jpegopt -> jpeg options `quality`, `progressive`, and `optimize` (only for jpeg format)
    thread_count -> How many threads we are allowed to spawn for processing
    userpw -> PDF's password
    use_cropbox -> Use cropbox instead of mediabox
    strict -> When a Syntax Error is thrown, it will be raised as an Exception
    transparent -> Output with a transparent background instead of a white one.
    single_file -> Uses the -singlefile option from pdftoppm/pdftocairo
    output_file -> What is the output filename or generator
    poppler_path -> Path to look for poppler binaries
    grayscale -> Output grayscale image(s)
    size -> Size of the resulting image(s), uses the Pillow (width, height) standard
    paths_only -> Don't load image(s), return paths instead (requires output_folder)
    use_pdftocairo -> Use pdftocairo instead of pdftoppm, may help performance
    timeout -> Raise PDFPopplerTimeoutError after the given time
In [ ]:
pages = convert_from_path('E:/jupyter-notebook-workspace/sample.pdf')
pages

Save pages into images

Save in JPEG format

In [ ]:
for page in pages:
    page.save('sample.jpg', 'JPEG')

View sample.jpg file.

Save in PNG format

In [ ]:
for page in pages:
    page.save('sample.png', 'PNG')

View sample.png file.

Thanks for reading.

In [ ]:
 

Machine Learning

  1. Deal Banking Marketing Campaign Dataset With Machine Learning

TensorFlow

  1. Difference Between Scalar, Vector, Matrix and Tensor
  2. TensorFlow Deep Learning Model With IRIS Dataset
  3. Sequence to Sequence Learning With Neural Networks To Perform Number Addition
  4. Image Classification Model MobileNet V2 from TensorFlow Hub
  5. Step by Step Intent Recognition With BERT
  6. Sentiment Analysis for Hotel Reviews With NLTK and Keras
  7. Simple Sequence Prediction With LSTM
  8. Image Classification With ResNet50 Model
  9. Predict Amazon Inc Stock Price with Machine Learning
  10. Predict Diabetes With Machine Learning Algorithms
  11. TensorFlow Build Custom Convolutional Neural Network With MNIST Dataset
  12. Deal Banking Marketing Campaign Dataset With Machine Learning

PySpark

  1. How to Parallelize and Distribute Collection in PySpark
  2. Role of StringIndexer and Pipelines in PySpark ML Feature - Part 1
  3. Role of OneHotEncoder and Pipelines in PySpark ML Feature - Part 2
  4. Feature Transformer VectorAssembler in PySpark ML Feature - Part 3
  5. Logistic Regression in PySpark (ML Feature) with Breast Cancer Data Set

PyTorch

  1. Build the Neural Network with PyTorch
  2. Image Classification with PyTorch
  3. Twitter Sentiment Classification In PyTorch
  4. Training an Image Classifier in Pytorch

Natural Language Processing

  1. Spelling Correction Of The Text Data In Natural Language Processing
  2. Handling Text For Machine Learning
  3. Extracting Text From PDF File in Python Using PyPDF2
  4. How to Collect Data Using Twitter API V2 For Natural Language Processing
  5. Converting Text to Features in Natural Language Processing
  6. Extract A Noun Phrase For A Sentence In Natural Language Processing