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:
Convert docx to pdf on Windows or macOS directly using Microsoft Word (must be installed).
pip install docx2pdf
Python module is installed. Open Jupyter notebook and import module.
!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.
from docx2pdf import convert
folderDir = "E:/jupyter-notebook-workspace/"
inputFile = folderDir + "sample.docx" outputFile = folderDir + "sample.pdf"
0%| | 0/1 [00:00<?, ?it/s]
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 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.
pip install mammoth
with open(inputFile, "rb") as docx_file: result = mammoth.convert_to_html(docx_file) html = result.value # The generated HTML messages = result.messages
'<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>'
f = open(folderDir + 'sample.html',"w") f.write(html) f.close()
We have saved file in sample.html. Let us view the sample.html.
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 users will have to install poppler for Mac.
Most distros ship with pdftoppm and pdftocairo. If they are not installed, refer to your package manager to install poppler-utils
Install poppler: conda install -c conda-forge poppler Install pdf2image: pip install pdf2image
pip install pdf2image
conda install -c conda-forge poppler
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
pages = convert_from_path('E:/jupyter-notebook-workspace/sample.pdf') pages
for page in pages: page.save('sample.jpg', 'JPEG')
View sample.jpg file.
for page in pages: page.save('sample.png', 'PNG')
View sample.png file.
Thanks for reading.