泰晓科技 -- 聚焦 Linux - 追本溯源,见微知著!
网站地址:https://tinylab.org

儿童Linux系统,可打字编程学数理化
请稍侯

Centering (horizontally and vertically) an image in Latex

Wu Zhangjin 创作于 2014/01/02

by falcon of TinyLab.org 2014/01/02

Background

In Open-Shell-Book project, I want to add an image as the book cover.

First off, I tried to convert the image to a pdf file with the convert.im6 tool from imagemagick, and then, used pdftk to merge this cover pdf file with the book pdf file, it basically worked, but the bookmarks lost.

$ sudo apt-get install imagemagick pdftk
$ convert cover.png cover.pdf
$ pdftk A=cover.pdf B=book.pdf cat A B output book-with-cover.pdf

Google gave me gs and pdf-merge.py, both of them didn’t work well, the former although reserved the bookmarks, but their links didn’t point to the right places, the latter fixed up part of the links, but also broke the accessing of the codes: the content listed as code can not be searched/copied in pdf readers.

Issue

So, I plan to use Latex itself to build the cover, but to do so, I must center the image horizontally and vertically.

Solution

To fix up this issue, after reading several pages of Google results, I get this solution:

  • Horizontally center the image with \begin{table} ... \end{table}
  • Vertically center the image with the export feature of the adjustbox package: \includegraphics[width=1.5\textwidth,center]{image.png}

The full code looks like:

\begin{table}
    \includegraphics[width=1.5\textwidth,center]{cover.png}
\end{table}

To simplify the using, our Open-Shell-Book defined a new command for the cover usage:

\documentclass[a4paper,oneside]{book}
\usepackage[export]{adjustbox}[2011/08/13]
\usepackage{graphicx}

\newcommand\makecover[1]{
    \clearpage
    \begin{table}
        \includegraphics[width=1.5\textwidth,center]{#1}
    \end{table}
    \addtocounter{page}{-1}
    \newpage}

\begin{document}

\makecover{cover.png}

\end{document}


Read Latest: