Converting MS Office Documents to PDF
Sometimes you have a Microsoft Office document, say an MS Word or MS PowerPoint file, and want to convert it to PDF.
If you do not have Microsoft Office installed, then you can do this via LibreOffice, which is free open source.
Here I provide the little Bash script office2pdf.sh, which does this in the Linuxterminal.
It basically just executes LibreOffice with the correct parameters.
All you have to do is to provide the path to the office document as parameter to the script.
It will then create a PDF with the same base name in the current folder, e.g., office2pdf.sh mydoc.docx creates the file mydoc.pdf in the current folder.
This should work with extensions such as .doc, .docx, .ppt, .pptx, .xls, and .xlsx.
If LibreOffice is not yet installed, it will automatically install it.
Here you can download this script and the complete collection of my personal scripts is available here.#!/bin/bash -
# Convert an MS Office document (doc, docx, xls, xlsx, ppt, pptx, ...) to pdf.
# The script expects a path to an MS Office file as input.
# It will create a document with the same name but .pdf as extension in the
# current directory.
# The conversion may not preserve some images correctly, but it more or less
# works.
# strict error handling
set -o pipefail # trace ERR through pipes
set -o errtrace # trace ERR through 'time command' and other functions
set -o nounset # set -u : exit the script if you try to use an uninitialized variable
set -o errexit # set -e : exit the script if any statement returns a non-true return value
srcDocument="$1"
dstDocument="$(basename "${srcDocument%.*}.pdf")"
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Converting '$srcDocument' to a PDF."
package="libreoffice"
if dpkg-query -W -f='${Status}' "$package" 2>/dev/null | grep -q "ok installed"; then
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): LibreOffice is installed, so we can use it."
else
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): LibreOffice is not installed. We install it now. This needs to be done only once."
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): We first update the package cache. This requires sudo privileges."
sudo apt-get update -y
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): We now install LibreOffice. This requires sudo privileges."
sudo apt-get install -y libreoffice
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Installation is finished."
fi
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Now converting '$srcDocument' to '$dstDocument'."
libreoffice --headless --safe-mode --convert-to pdf "$srcDocument" --outdir .
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Finished converting '$srcDocument' to '$dstDocument'."