Thomas Fischer's Weblog

Life, Linux, LaTeX

Archive for the ‘LaTeX’ Category

More on LaTeX Beamer: Linking images to an enlarged version

with 10 comments

If you have read my previous posting on LaTeX Beamer, you may remember that there were two example slides taken from a lecture of mine. Most slides for this lecture have a similar layout, consisting of a three-column table with fixed column widths. For photos to be shown in the right column, details become beyond recognition if the image or photo has a landscape-like aspect ratio or is scaled down by a large factor.

To circumvent this problem I came up with the idea of showing the small photo in full-screen size once clicked on; another click brings the viewer back to the original view. In terms of LaTeX, Beamer and PDF this means adding a new slide containing only the up-scaled photo and creating click-sensitive hyper-references (a.k.a. links) in both directions between the small image on the regular slide and the big-photo-only slide. As the big-photo-only slide should not interfere with the presentation if you do not click on the small photo, those special slides have to be appended at the very end of your presentation.

Thus, to solve the problem stated above, three subproblems have to be solved:

  1. Automatically creating a new slide at the end of your presentation
  2. Showing the photo in full-screen size
  3. Adding clickable links to jump between the regular slide and the big-photo-only slide

Of course, it should be as flexible and simple for the user as possible, so that it can be included in existing slide sets if necessary.

More Details

The process of creating slides for photos requires to scan through the document and memorize which photos to link to. This “memorization” is implemented in a LaTeX-like way by writing to a special .aux file using \newwrite and related commands. At the beginning, the file is opened for writing:


% open file linkimage.aux for writing images' filenames to it

The .aux file only stores image filenames. The links are later generated using the linkimagecounter counter, so that the first link always points to the first file etc.

Whenever there is an image to link, the user uses the \linkimage command:

% use this command to link some content to a large picture at the end of your slides
% create link anchor where link from document's end points to
% create link pointing forward to link source in frames at document's end
}} % close both hypertarget and hyperlink
% step counter

This command takes two arguments: First, the object which is the link source. This can be for example an \includegraphics, a \copyrightbox, or a \beamerbutton command. The second argument is the image’s filename; no includegraphics statement should be used here, as this will be called automatically when generating the big-photo-only slides.
\linkimage{\copyrightbox{\includegraphics[height=3em]{photo2}}{Thomas Fischer}}{photo2}
\linkimage{\beamerbutton{Show Photo}}{photo2}

Finally, at the end of your slide set after the slide with “questions now, please”, you have to call \flushlinkimages which will insert all big-photo-only slides.

% call this command at the very end of your presentation (even after "Now questions, please" slide)
% internal counter for loop over all linked images

% close auxiliary file linkimage.aux and re-open it again for reading

% loop over all linked images ...
% read one line (one image filename) at a time (and strip new line character at end)
\endlinechar=-1\immediate\read\linkimageinputstream to \linkimagefilename
% create a new frame per image, center content
% create link pointing backward to link source in main document
% create link anchor where link from main document points to
}% hypertarget
}% hyperlink
% step counter
} % whiledo
% close file

In above code, first some counters are initialized. As you remember, we use counters to match images and hyper-references. Next we close our .aux file (still open for writing) and open it for reading. This makes a single LaTeX run sufficient to generate the extra slides, as the .aux file is written and read in one pass.

The interesting part is the loop, going through all photos. In each iteration, one filename is read from the .aux file and a simple frame environment is created holding an \includegraphics command maximizing the photo while keeping its aspect ratio. You may have to adjust the height parameter for your personal Beamer theme. Hyper-references (\hyperlink and \hypertarget) are generated as well, corresponding the commands created in the original \linkimage call.

As a clarification: All the LaTeX code above should be placed in a class or style file to be included in your presentation. Within your presentation, you should only use \linkimage and \flushlinkimages, everything else happens automatically.

I would be interested in hearing from you if you see ways to make it more efficient, simpler, or more flexible.


Written by Thomas Fischer

September 7, 2010 at 16:05

Posted in LaTeX

Some new LaTeX Beamer Tricks

with 7 comments

The Swedish summer fades into a rainy autumn, which means it is time again to prepare lectures for the coming months. As a long-time LaTeX user, I use the LaTeX Beamer package for all my slides. During the last few months, I have developed some new helper commands and environments for LaTeX slides, which I want to present here.

The multiframe environment

The Beamer package’s frame environment has the option allowframebreaks to automatically split a frame once it becomes full or split frames manually using the \framebreak command. Although this solution works, it has two drawbacks:

  1. No animation steps can be included using e.g. \only or \pause.
  2. The first frame is such a sequence of “split” frames sets its content with a slightly different vertical offset. This is very annoying, because flipping between slides makes the content jump up and down.

Therefore I designed my own solution. Although it is not perfect, it does not show above flaws. The idea is to define a new environment called multiframe via newenvironment and accept one optional parameter. This new environment acts as a replacement for the known frame environment. An important difference is the optional parameter: Whereas Beamer’s original frame parameter accepts a list of options such as allowframebreaks or fragile, multiframe‘s parameter is the frame’s title. Thus, the frame title is no longer set via \frametitle but with this parameter.

Now, the trick to get a sequence of frames is to omit the optional parameter with subsequent frames. In this case, the multiframe environment assumes that this new frame is part of sequence, reuses the previous frame title, but increases the sequence counter as shown in the title.

% new counter to now which frame it is within the sequence
% initialize buffer for previously used frame title
% new environment for a multi-frame
% if no frame title was set via optional parameter,
% only increase sequence counter by 1
% new frame title has been provided, thus
% reset sequence counter to 1 and buffer frame title for later use
% start conventional frame environment and
% automatically set frame title followed by sequence counter

Drawback with this solution is that it creates a completely new frame, whereas \framebreak can be used (nearly) everywhere in the frame. For example, you can use \framebreak inside an itemize list and split this list. In my solution, you have to close all environments up to the current multiframe and open again all environments as desired.


Without my new environment, you would set plain, single frames using the frame environment. Nothing changes here:

\frametitle{The Frame's Title}
Some content \ldots

Things get different for sequences of frames. With plain LaTeX Beamer, you would do something like this:

\frametitle{The Frame's Title}
Some content \ldots
More content on next page

With my new environment, the corresponding solution would look like this:

\begin{multiframe}[The Frame's Title]
Some content \ldots
\only<2>{Only seen in animation step}
% this is like a frame break
\begin{multiframe}% no optional parameter here!
More content on next page

The copyrightbox Command

When you include photos, images, or drawing on your slides, you should always give credit to the original creator and show license and origin. Some licenses require you to state where you got the image from and which rights have been granted. For someone who wants to reuse your slides or parts of it, it clarifies under which conditions the materials are accessible. From a legal aspect, it suffices in most cases to show all relevant information next to the included image, or collected at the end of your document in a single list.

In the next-to-the-image case, it is common to set the information text in fine print along the bottom or right border of the image. But how to do it in LaTeX? For the solution I am presenting here, I am using a tikzpicture environment to set both the image and the accompanying text in two nodes next to each other. The new command \copyrightbox takes two mandatory parameters and one optional parameter. The first mandatory parameter is supposed to contain the command showing the image or drawing, e.g. an \includegraphics command. The second parameter takes the copyright statement and is usually plain text. The optional parameter is a single character describing the position of the text in relation to the image. Possible values include b (below), l (left), and r (right), where “right” is default if nothing else is specified.

Now, the tricky part is that the image should determine the copyrightbox‘s size and the text should follow this format. In particular, if the text is below the image, the text (more specific, the node containing the text) should be node wider than the image (more specific, the node containing the image); instead it should wrap around consuming several lines if necessary. The same applies to the height in case of left or right alignment. To get the width and height of a node in TikZ, I had to search for a proper solution on the Internet resulting in a quite long statement for commands ydiff and xdiff.

    \coordinate (tmpnamea) at (#1);%
    \coordinate (tmpnameb) at (#2);%
    \advance\ydiffl by -\tu@tmpa%
    \coordinate (tmpnamea) at (#1);%
    \coordinate (tmpnameb) at (#2);%
    \advance\xdiffl by -\tu@tmpa%
\node[inner sep=0pt,minimum size=2em](ciimage){#2};
\node[inner sep=0pt,right=1ex of ciimage.south east,anchor=north west,rotate=90]%
\node[inner sep=0pt,right=1ex of ciimage.south west,anchor=south west,rotate=90]%
\node[inner sep=0pt,below=1ex of ciimage.south west,anchor=north west]%


To use this new command, you simply set the mandatory parameters with some useful values:

\copyrightbox{\includegraphics[width=0.5\linewidth]{images/osmphoto}}{CC-BY-SA, Thomas Fischer}
\copyrightbox[b]{\includegraphics[width=0.5\linewidth]{images/osmphoto}}{CC-BY-SA, Thomas Fischer}

The first example above creates a copyrightbox containing an image as loaded from images/osmphoto.jpg (pdflatex searches for known extensions if you do not specify one), scaled to 50% of the line width, and the copyright statement “CC-BY-SA, Thomas Fischer”. The text will be written on the image’s right side, starting in the lower right corner going upwards. In the second line, the text’s alignment is changed to b: Here the text starts in the lower left corner and goes to the right as usual.

Be aware that the copyrightbox‘s total size is a combination of both the image and text. It will thus be larger than the image alone (as specified with width or height).

Written by Thomas Fischer

August 17, 2010 at 18:52

Posted in LaTeX

Videos on using KBibTeX

with 4 comments

KBibTeX has several nice features which simplify your daily work when you edit BibTeX files. In this blog post, I’d like to show you three small videos on some basic operations in KBibTeX.

The most basic operation is to add a new entry, which is demonstrated in the first video:

Video on how to add a new entry in KBibTeX

Video on how to add a new entry in KBibTeX

The second video shows you how to search for a reference on the Internet. In this example, Google Scholar is used to find a reference on Robert Sedgewick’s `Algorithms in C++’:

Video on how to use Google Scholar in KBibTeX

Video on how to use Google Scholar in KBibTeX

In the last video, duplicates in a BibTeX file are found and merged into a single entry. When merging entries, you can interactively select the fields to be kept in the resulting entry.

Video on how to find and merge duplicates in KBibTeX

Video on how to find and merge duplicates in KBibTeX

P.S. I’d like to thank my sister for dubbing the videos.

Written by Thomas Fischer

October 27, 2008 at 12:40

Posted in KDE, LaTeX

Pretty printing LaTeX tables

with one comment

AWK is a really nice tool regarding processing text automatically. Here, I’d like to show you an example how to use AWK to pretty print tables in LaTeX source code.

The AWK script itself is a one-liner. It reads your table from stdin (simply copy&paste to your terminal) and writes the formatted table to stdout. It is assumed that one table row corresponds to one line in the input data. The script checks for the widest cell in each column (number of characters) and aligns the output so that the &s are vertically aligned. The first column will be left-aligned, all other columns are right-aligned.

And here is the script (you can put everything in one line when removing all \):

awk -F '[\\t ]*([&]|\\\\\\\\)[\\t ]*' 'BEGIN { maxcol=0 } \
  { for (i=1; i<=NF; ++i) cell[NR,i]=$i; if (NF-1>maxcol) \
  maxcol=NF-1 } END { for (c=1; c<=maxcol; ++c) { \
  colwidth[c]=0; for (r=1;r<=NR; ++r) if \
  (length(cell[r,c])>colwidth[c]) colwidth[c]= \
  length(cell[r,c]); }; for (r=1; r<=NR; ++r) { printf \
  "%s%"(colwidth[1]-length(cell[r,1]))"s", cell[r,1], ""; \
  for (c=2; c<=maxcol; ++c) printf " & %"colwidth[c]"s", \
  cell[r,c]; print " \\\\" } }'

Finally, a before and after example:

 &1 & 2& 3  & 4&5 &  6 \\
Square & 1  &  4& 9 & 16  & 25& 36         \\
Faculty  & 1 & 2 & 6  &  24 &  120  & 720  \\
Exp  & 2.72 &  7.39  &  20.09 & 54.6  & 148.41 & 403.43  \\
        &    1 &    2 &     3 &    4 &      5 &      6 \\
Square  &    1 &    4 &     9 &   16 &     25 &     36 \\
Faculty &    1 &    2 &     6 &   24 &    120 &    720 \\
Exp     & 2.72 & 7.39 & 20.09 & 54.6 & 148.41 & 403.43 \\

There is also a shell script calling the above AWK script:

Download script

Update: The script has been modified to support multicolumn commands a little bit better.

Update 2 (2009-03-20): In a discussion with Günther, we came up with a real small solution.

sed -e 's/\s* / /g;s/&/ ~& /g' | column -s '~' -t

However, it may fail under certain circumstances (e.g. when using \&), but it is small and beautiful 😉

Written by Thomas Fischer

May 12, 2008 at 0:00

Posted in LaTeX, Linux

Text on PDF Files

leave a comment »

As promised last time, I’m going to show a small bash script which puts text on existing pdf files. This bash script uses pdflatex, some styles and auxiliary programs to do its magic. The script is currently work in progress, thus feedback is welcome.

Once the script is placed somewhere in the path, you can apply it to any pdf document. The scripts parameters are group into three categories:

  • Global parameters:

    Prints help on parameters
    Puts all boxes (see below) above any content in the pdf file. May be neccessary under certain circumstances.
    -p prefixfile
    Insert additional commands (e.g. \usepackage) into document prefix
  • I/O parameters:

    -i infile
    Input file’s name
    -o outfile
    Optional argument for the output file’s name. If no name is given, the input file’s name will be used and appended by -textonpdf
  • Box parameters. Boxes are text frames with coordinates (x/y), width and a textual content. Multiple boxes may be defined, each textual content will be placed at the coordinates specified in previous parameters

    -x number
    absolute x-coordinate of the next box, given in cm
    -y number
    absolute y-coordinate of the next box, given in cm
    -w number
    width of the next box, given in cm
    -t text
    textual content of the box. Occurrences of %d will be replaced by the current date, %p will be replaced with the current page’s number

    Boxes will be put on every page. The boxes’ content is centered.

Let me show you some examples: -x 0 -y 27 -w 21 -t '%p' -i myfile.pdf -o output.pdf

will put page numbers (as given by -t '%p') centered (given a page is 21cm wide) at the bottom of each page (27cm below the top). As promised, multiple boxes may be specified. The following example puts the current date on the top of each page: -x 5 -y 27 -w 11 -t '%p' -x 2 -w 17 -y 2 \
  -t 'File created on \textbf{%d}' -i myfile.pdf -o output.pdf

As you can see, LaTeX commands can be used in the inserted text, as the boxes’ content is directly used in the intermediate tex document. Updated: Finally, a more complex example for a watermark. First, we create a prefix file, which will be loaded using the -p switch.


These packages load Helvetica as font, set the input encoding to UTF-8 (may be different for you), and include the rotating and xcolor package. Now, we call the script: -x 1 -y 1 -p prefix.tex -w 10 -t \
  '\centering\begin{turn}{25}\begin{minipage}{10cm}\centering\bfseries\sffamily\Huge\color{red}Nur für den\\internen Gebrauch\end{minipage}\end{turn}' \
  -i test.pdf -o test2.pdf

Here, you can two new things: First, the prefix file prefix.tex (see above) and include some tex commands into the text at the -t switch. In the text, there are commands to turn the text by 25 degrees and a minipage of 10cm widths (required for the line break later). Inside the minipage, all text is centered, set in Helvetica, huge and red. The text itself is a two lines long and warns you the document is for internal use only. Using or removing the -l switch makes a difference.

Does it work for you, too? Any bugs or comments? Let me know.

Download script

Written by Thomas Fischer

April 27, 2008 at 0:00

Posted in LaTeX, Linux

Modifying PDF Files with Command Line Tools

leave a comment »

Sometimes it is neccessary to edit a pdf file e.g. by extracting selected pages, putting multiple pages on one page or changing the page margins. For all these problems there is a toolchain called PDFjam.

PDFjam is a collection of shell scripts that use pdfLaTeX to perform modifications on a (set of) pdf documents. Installing PDFjam is quite simple, as most Linux distributions offer packages.

PDFjam consists of three shell scripts:

Puts multiple pages on one pages, may perform additional operations such as scaling. The PostScript equivalent for this tool is psnup.
Combines multiple pdf documents into one file, may perform additional operations.
Rotates pages in 90 degree steps.

For PostScript documents, similar operations can be performed using the PSUtils or mpage.

I’m going to present some typical use cases where you want to use the PDFjam tools:

  1. You got slides from a lecture or presentation. Each slide is one page in the pdf document and it is a waste of paper (and trees ;-)) to print it this way. To put 2×4 pages on one page, use the following command:
    pdfnup --nup 2x4 slides.pdf

    The result file will be called slides-2x4.pdf. Now, you may want to have some margin around these eight slides on each page, e.g. to add personal notes or for punching. Simply scale the page’s content:

    pdfnup --nup 2x4 --scale 0.9 slides.pdf

    Adapt the scale parameter to your personal needs. To have space between each of the eight slides, add the --delta parameter:

    pdfnup --nup 2x4 --scale 0.9 --delta "1cm 1cm" slides.pdf

    Here, between two slides one centimeter is added in horizontal and vertical direction. Of course, you can use this program not only for slides, but you can put two pages on one side of a sheet of paper, too. In this case, use --nup 2x1.

  2. You got a set of pdf documents from several sources and you want to combine them to one single document. E.g. from SpringerLink you can get whole books split into single files per chapter or section. To recombine a sequence of pdf files to one pdf file, use the following command:
    pdfjoin --outfile book.pdf  chapter1.pdf chapter2.pdf ...

    Parameter --outfile determines the resulting pdf file’s name.

Both pdfjoin and pdfnup provide many more options to scale, rotate, or crop the files to be processed. Simply use the parameter --help to get an overview of all available options.

Next time, we will have a look on how to add text or any other content into existing pdf documents …

Written by Thomas Fischer

April 25, 2008 at 0:00

Posted in LaTeX, Linux

Präsentationen mit Folie

leave a comment »

An der Universität und auf Konferenzen kommt man viel mit Vorträgen in Berührung. Ein unterstützendes Element für jeden Vortrag sind die Folien. Einige Beispiele, was man alles falsch machen kann, möchte ich in diesem Blog-Beitrag vorstellen. Die hier vorgestellten Folien sind Nachbauten real-existierender Folien, die ich zum Schutz der Persönlichkeit nicht direkt zeige.

Viel Text auf Folien

Viel Text

Leute lesen gerne. Also, warum sollte man ihnen nicht viel Text vorsetzen? Ziel von Vorträgen ist es, Informationen kurz und präzise auf den Punkt zu bringen. Das unterscheidet eine Präsentation von der dazugehörenden Ausarbeitung, wo ins Detail gegangen wird und jeder Satz ausgefeilt wird.

Es ist natürlich verlockend, den Text aus der Ausarbeitung direkt auf die Folie zu kopieren, schließlich steckt da ja schon Arbeit drinnen. Wenn dann diese Folien aufgelegt werden, gibt es zwei Verhaltensweisen: Entweder der Vortragende liest den Text Wort für Wort vor (beliebt bei Leuten, die nicht frei sprechen können oder die Sprache nicht sicher beherrschen) oder der Vortragende erzählt den Inhalt mit eigenen Worten und der Zuhörer muss sich entscheiden, ob er zuhört oder liest.

Meiner Meinung nach sind Aufzählungspunkte (evtl. gestaffelt, maximal zweizeilig) mit Satzfragmenten in den meisten Fällen die beste Darstellungsform. Einzige Ausnahmen, wo mehrzeilige Textpassagen erlaubt sind, sind Zitate (möglichst knapp halten und immer Referenz nennen) oder Definitionen.

Spielen mit Farben


Farben sind eine tolle Sache: Man kann damit viele Informationen schön sauber getrennt visualisieren. Problem ist, daß man sich nicht immer darauf verlassen kann, wie die Licht- und Präsentationsverhältnisse vor Ort sind. Es kommt öfters vor, daß eine helle Deckenlampe auf eine Leinwand scheint und den Kontrast der projezierten Folie reduziert. Dünne Linien auf einem Hintergrund mit ähnlicher Farbe helfen auch nicht weiter. Vielleicht sehen nicht alle Zuschauer sehr gut oder sind farbenblind.

Diese Überlegung machen nicht alle, denn es kommt durchaus vor, daß grau auf blau gesetzt wird (siehe Beispiel). Schwacher Kontrast und schwer lesbare Folien ermüden den Leser/Zuhörer, macht das Verstehen von Beispielen schwierig und schließlich verliert man den Zuhörer komplett. Viel besser ist es, Folien mit weißem oder sehr hellem Hintergrund und dunkler Schrift zu verwenden. Das mag vielleicht konservativ wirken, dafür kann es jeder lesen. Wird eine Grafik sowohl in einer schriftlichen Veröffentlichung, als auch in der Präsentation verwendet werden, sollte die Papierfassung schwarz-weiß mit dünnen Linen und die Folienfassung bunt, aber mit wesentlich dickeren Linien und größerer Schrift dargestellt werden.

Folien mit Informationen überladen

Riesige Tabelle

Eine Folie, die auf mehrere Quadratmeter vergrößert wird, macht es verlockend, riesige Informationsmengen darauf unterzubringen. Problem ist, daß man damit seine Zuhörer überfordert. Wenn sich ein Zuhörer für Details interessieren sollte, kann nach dem Vortrag nachgefragt oder -gelesen werden.

Wie das Beispiel rechts zeigt, sind nicht alle Vortragende der gleichen Meinung. Schließlich wurde viel Zeit und Aufwand in Versuche gesteckt, also warum sollte man diese Informationen nicht zeigen? Die Antwort ist einfach: In dieser riesigen Datenmenge sieht niemand, was der wissenschaftliche Beitrag des Vortrags ist. Weniger ist mehr, wenn man sich auf ausgewählte Werte beschränkt und diese dafür um so detailierter beschreibt.

Graphen und Plots


Plots sind ein Thema für sich: Bei der Visualisierung von Daten muss natürlich die richtige Darstellungsform gewählt werden und die Daten auch in den richtigen Kontext gestellt werden. Visualisierungsprogramme wie GNUPlot oder OpenOffice Calc bieten eine große Auswahl an Darstellungstilen und nicht jeder Vortragende hat ein Gespür für die richtige Technik.

In dem Beispiel rechts ist auf wird unterstellt, daß die horizontal verlaufenden Linien einen sequentiellen Zusammenhang (z.B. Wertentwicklung über Zeit) darstellen. Tatsächlich listet die X-Achse nur die Instanzen auf; deren Reihnfolge ist aber willkürlich und somit auch der Linienverlauf im Plot.

Folien richtig machen

Und wie macht man jetzt Folien richtig gut? Das ist fast schon eine Wissenschaft an sich. Es hängt ab vom persönlichen (Vortrags-)Stil, Zielpublikum, Art und Umfang der zu präsentierenden Informationen, Zeitrahmen und weiteren Faktoren. Lesenswert zu dem Thema ist u.a. das Presentation Zen.

Ich persönlich benutze das Beamer-Paket mit LaTeX, zu dem ich einen einfachen Stil selber entwickelt habe. Einfacher Aufbau, nicht überladen, kontrastreiche Farben (schwarz/blau auf weiß).

Eigene Folien im Einsatz

Written by Thomas Fischer

April 29, 2007 at 0:00

Posted in LaTeX, University