Affichage des articles dont le libellé est latex. Afficher tous les articles
Affichage des articles dont le libellé est latex. Afficher tous les articles

lundi 23 avril 2012

Impression de planches d'étiquette avec Latex (publipostage)

Je m'occupe d'une association avec laquelle nous faisons de temps en temps du mailing "classique" (par la poste!) en générant des planches d'étiquettes autocollantes à partir d'un fichier de contacts maintenu sous la forme d'un fichier "tableur".
Pendant longtemps, je me suis acharné, (voire épuisé!) avec les "fonctionnalités" de publipostage des suites bureautiques classiques.
Cette fonctionalité, pourtant à priori basique, est en effet difficile à manier, du moins sur les versions que j'ai pu essayer (Office 2003 et OOo 3.3). On passe des heures à créer un modèle, à cliquer, à en enregistrer les versions successives, à identifier le format parmi les formats prédéfinis, à cliquer, à ouvrir la base de données (qu'il faut aller rechercher dans l'arborescence à chaque fois...), à fusionner, à recommencer parce qu'on a un message disant "impossible de trouver la source de données" ou quelque chose du genre, à recliquer, à re-naviguer jusqu'au dossier, à cliquer encore, à re-générer, à essayer autre chose, à re-naviquer, à re, à re, etc.
L'enfer! Pour quelque chose qui au final, peut fonctionner, mais surtout a un comportement erratique: un coup, c'est bon, un coup, c'est pas bon....

Bref. Insupportable.

A coté de ça, on trouve aussi des logiciels, libres ou propriétaires, qui vous proposent de faire peu ou prou la même chose. Mais bon, encore un bidule à installer, qui ne va pas forcémment être exactement adapté à ce que vous voulez...

Je refléchissais depuis quelque temps sur la possibilité d'une solution automatisée 'en 1 clic', utilisant des solutions éprouvées, libres et multiplateforme, mais faute de temps, j'avais laissé ça un peu de coté. Etant utilisateur quotididien de Latex, j'ai presque par hasard recherché s'il n'y avait pas un package qui m'aiderait dans cette tâche. Et là, Bingo!
Premier hit: le package "labels", qui fait... tout!
Pour la faire courte, et pour les familiers de Latex, il suffit du petit source suivant. Pour les autres, c'est peut-être une excellente occasion de se mettre à Latex ?

\documentclass{article}
\usepackage{labels}

\begin{document}
\begin{labels}
\input names.dat
\end{labels}
\end{document}

Et le tour est joué: après compilation, vous disposez d'un pdf avec les étiquettes, à condition que vous fournissiez dans le dossier courant le fichier names.dat contenant les noms et adresses au bon format (voir ci-dessous). Evidemment, en général, on devra personnaliser un peu, ajouter babel pour l'alphabet occidental, le nombre de lignes et de colonnes, etc. On peut évidemment régler les marges et autres espacements avec les commandes adéquates, la doc est très complète là dessus, et l'archive de téléchargement contient en bonus une multitude d'exemples.

# my_labels.tex

\documentclass[a4paper,12pt]{article}
\usepackage[french]{babel}
\usepackage[utf8]{inputenc}% ou iso8859-15 en général sur windows
\usepackage{labels}

\LabelCols=2
\LabelRows=7

\begin{document}
\bfseries
\begin{labels}
\input names.dat
\end{labels}
\end{document}

Pour le format des données, ce package n'attend pas de format particulier: il se contente d'imprimer sur les étiquettes le texte fourni, ligne par ligne, avec comme séparateur d'étiquette un simple saut de ligne. Comme par exemple (tiré de la doc):

Professor R. Bercov, Chair
Department of Mathematics
University of Alberta
Edmonton, Alberta
Canada T6G 2G1

Chair of the Search Committee
Department of Mathematics
and Statistics
University of Regina
Regina, Saskatchewan
Canada S4S 0A2

...

Il faudra donc commencer par exporter les données au format csv, puis procéder à un petit traitement pour générer ce fichier, et ensuite lancer Latex dessus. Sur plateforme Linux standard l'ensemble des outils nécessaires est normalement disponible, pour Windows, c'est faisable, mais un peu plus délicat.

D'abord, il faut expurger préalablement le fichier .csv des guillemets qui peuvent avoir été générés par le tableur (Il semble qu'OOo génère systématiquement ces guillemets autour des cellulles contenant du texte). On peut faire ça à la main via un "rechercher/remplacer" dans son éditeur favori, mais c'est plus élégant et surtout plus fiable de faire ça avec un outil dédié: sed

Depuis le shell, la commande
sed s/XXXX/YYYY/ input_file > output_file
va remplacer dans le fichier d'entrée input_file la première occurence de 'XXXX' par 'YYYY'. La sortie de programme se fait par défaut sur la "sortie standard" (la console), et il faut donc la rediriger vers le fichier souhaité (output_file) via le caractère de redirection '>'.

Pour remplacer toutes les occurences, on ajoute un 'g':
sed s/XXXX/YYYY/g input_file > output_file
Pour éliminer les occurences d'une chaine, il suffit de laisser YYYY vide.

En général, la première ligne du fichier contient le nom des colonnes, et il faut donc la supprimer. sed permet ceci avec la syntaxe:
sed 1d input_file > output_file
Pour regrouper les 2 commandes en une ligne, il faut ajouter l'option -e indiquant que la chaine qui suit est une commande:
sed -e 1d -e s/XXXX/YYYY/g input_file > output_file

Au final la commande est donc:
sed -e 1d -e s/\"//g ooo_export.csv > adresses.csv
(il faut "backslasher" le guillemet)

Un exemple de script bash est donné ci-dessous, qui enchaîne les 3 passes:
- preprocessing du fichier csv,
- génération du fichier d'adresses,
- appel de pdflatex pour la génération du pdf final.
Il faudra aussi adapter l'ordre des champs à ce que vous avez dans votre fichier d'origine.

#! /bin/bash

outfile=names.dat
sed -e 1d -e s/\"//g ooo_export.csv > adresses.csv

echo "" > $outfile

# var. spéciale: séparateur de champ
IFS=';'

while read LINE; do
 echo "$LINE";
 a=( $LINE )
 LNAME=${a[0]}
 FNAME=${a[1]}
 ADR=${a[2]}
 CODE=${a[3]}
 CITY=${a[4]}

 echo "$FNAME $LNAME"  >> $outfile
 echo "$ADR"  >> $outfile
 echo "$CODE $CITY"  >> $outfile
 echo "" >> $outfile

done < adresses.csv

pdflatex -interaction=batchmode my_labels.tex

Attention:
On a parfois dans les fichiers d'adresses des champs du style "Gérard & Jacqueline". Latex interprétant le '&' comme un caractère spécial, mieux vaut le supprimer de votre fichier source et remplacer par "Gérard et Jacqueline". Autre solution : "Gérard \& Jacqueline".

La suite ? Réaliser un export en ligne de commande du fichier d'adresses originel... Mais OOo ne semble pas disposer de cette fonctionnalité là, il faudrait passer par d'autres outils tiers.

Edit 10/2012: en fait, l'export en .ods  (Open Document Spreadsheet) depuis le fichier Excel de départ permet de disposer d'un fichier xml du contenu, dont on peut extraire le contenu. OpenDocument Fellowship propose des outils pour manipuler les fichiers Open Document, mais qui semblent à ce jour ne concerner que les fichiers odt (de type "texte", donc, et pas les feuilles de calcul ods).

L'autre approche consisterait à écrire un parser adéquat, qui récupère  les champs et les copie dans le fichier décrit ci-dessus.  pyxml semble l'outil le plus adapté, une piste à suivre...

Edit 02/2015: LibreOffice 4.2 (et OpenOffice ?) propose désormais un outil en ligne de commande qui permet d'exporter un fichier .ods en .csv, avec la syntaxe suivante:
libreoffice --headless --convert-to csv *.ods

mercredi 30 septembre 2009

Integrating a LaTeX/Beamer build system under Windows shell



I'm a LaTeX user for a couple of years now, but I only switched to beamer presentation this summer. I always was quite impressed in conferences or other events by the presentations that were made with beamer. At that time, I was happily using MS PowerPoint, but over the time, I felt more and more unsatisfied with mine.
"Beamer guys" presentations looked always cool, the slides were clean, clear and classy. Woah ! I had to switch...

So I recently gave it a try, and I must say at present, I don't think I will ever come back to MS.

I intend to prepare some kind of a tutorial on Beamer, as there's not that much out there specifically on beamer, and I already know some useful tricks. But today I will focus on another point, not directly LaTeX-related, but about a usability trick for building different pdf files, while needing an identical presentation standard for all the documents, and needing each document in different modes. This happened to me when preparing courses. I do a lot of teaching, and I always give a paper handout to the students, so they can focus on what I'm saying, rather than handwriting notes.

With LaTeX, when you are building several documents that must share the same presentation, keeping a consistent header can quickly become tedious. You often need to tweak it, add a package, change a package option, ... If you are working on several documents at once, it's easy (understand: unavoidable) to end up with differents headers in your different documents. And you get slight (or heavy...) aspects changes in the final documents. Moreover, you are likely to forget which header is the correct one.

One way to handle to this is to concentrate on your part of the document, that is, what starts after \begin{document} and ends before \end{document}. All the rest is about formating information, and should be common to all documents.
Just let an automated script do the painful job (adding the header, and calling the compiler). And as I like fooling around with windows shell, I present here an example of what can be done in such a context. For a quick idea, when I'm done editing my file, I just call the right-clic menu on it, and here it goes...

Before:



After:




And I get my ready-to-use pdf file, with the right formatting, and compiled in the right mode:



For now, three different building modes are available:

  • the standard beamer version, with all overlays,

  • a 4 on 1 handout printable version,

  • and a 1 on 1 version, same as the beamer version, but with no overlays, useful for quickly checking page rendering.


And of course, if I need fine-tuning of the LaTeX stuff, I still have the (generated) .tex file in my folder.

If you only want to get the thing working, you can skip the rest, and go directly at the bottom to download. Else, I'll explain how the trick works. Please be adviced that this needs some knowledge about how an OS and a computer works. In my case, it is MS Windows (XP for me, but should be fine on others) and its standard "cmd" script langage, but Linux users should be able to translate in their own shell (at least, experienced Linux users...)

First, your file. As I said, it starts with
\begin{document}
and ends with
\end{document}
You need a title page, on which will be written your name, date, and... the title. So the first lines of the document will look like:
\begin{document}
\title[small title in footer]{Main Title On First Page}
\begin{frame}
\titlepage
\end{frame}
The date is usually set up automatically, and the authors name isn't something that changes every day, so it can be lying in a the header template. These settings can be of course overridden.
\begin{document}
\title[small title in footer]{Main Title On First Page}
\date{2050}
\author{Gill Bates}
\begin{frame}
\titlepage
\end{frame}
Ok, now, how about compiling ? This is done by a simple batch file, that basically concatenates three files: "mode" header, regular LaTeX header, and your document. On Windows, it goes like this (Linux users will tweak this easily):
copy /A "%mp%\head_beamer.tex"+"%mp%\common_header.tex"+"%fn%.texb" "%fn%.tex" > nul
pdfLaTeX.exe --interaction=batchmode "%fn%.tex" 1> LaTeX_log_stdout.txt 2> LaTeX_log_stderr.txt
'mp' is the path where the script and template headers lie, anf 'fn' is the file name. 'head_beamer.tex' is the short header that defines the mode 'beamer', while 'common_header.tex' is where the "real" header stuff goes.

Ok, and how do you choose the right header ? Well, this is really windows specific, as it is about it's registry, and I don't know how you define this with Linux.

To make it short, with Windows, each file extension defines a "type" of file, and each type gets associated with some things you can do with it. This information is stored in the so-called "registry". This can be (badly) handled through the 'assoc' cmd command, or using the 'regedit' GUI. But the best way is to write a .reg file, that will automated this process.

First, we define a new file extension: ".texb"(.tex + B for beamer), in order to avoid changing the default .tex file behaviour you have on your system :
[HKEY_CLASSES_ROOT\.texb]
@="LaTeX.BeamerBody"
And associate this file type (LaTeX.BeamerBody) with the corresponding commands:
[HKEY_CLASSES_ROOT\LaTeX.BeamerBody\shell\build_B]
@="Build (Beamer version)"
[HKEY_CLASSES_ROOT\LaTeX.BeamerBody\shell\build_B\command]
@="\"C:\\program files\\sk_scripts\\BuildWithBeamer\\BuildWithBeamer.bat\" \"%1\" B"
The 'B' letter at the end of the command is an argument that is passed to the script, so it gets the right header. For example, the 'beamer' header will look like this:
\documentclass{beamer}
\usetheme{Madrid}
the 'handout' version like this:
\documentclass[handout]{beamer}
\usetheme{Madrid}% change this to whatever beamer theme you want
and the 'handout 4 on 1' like this:
\documentclass[handout]{beamer}
\usetheme{default}
\selectcolormodel{gray}
\usepackage{pgfpages}
\pgfpagesuselayout{4 on 1}[a4paper,landscape,border shrink=1mm]
\pgfpageslogicalpageoptions{1}{border code=\pgfsetlinewidth{1.5bp}\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{2}{border code=\pgfsetlinewidth{1.5bp}\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{3}{border code=\pgfsetlinewidth{1.5bp}\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{4}{border code=\pgfsetlinewidth{1.5bp}\pgfusepath{stroke}}

% because the 'default' does not add page numbers
\addtobeamertemplate{footline}{\insertframenumber/\inserttotalframenumber}
All this 'pgf' stuff is there to define a solid border around each slide, as the 'default' beamer theme is quite sober (thanks to all the guys on this excellent french-spoken LaTeX mailing list for this trick.)

So what if you want to have this shell menu available on your system ? Well, all this configuration is provided in this zip file: download, unzip, and launch Install.bat. This will copy everything in convenient places, and import settings in registry. You're ready to go, assuming, of course, you have a working LaTeX installed, and available in the path (I use MikTeX).

And of course, an 'uninstall' is provided, to remove the settings from the registry. Once you have this installed, you can check it by going down in the 'demo' folder, and double-clic the file 'demo.texb': it should produce a nice example pdf !

Q & A

Q: what if I don't like the theme you choose ?
Q: what if I want to change colors ?
Q: what if I want to add a package ?
Q: what if I wan't to remove your stupid badly designed logo I get on every page ?
A: All these questions have the same answer: just edit the file c:\program files\sk_scripts\BuildWithBeamer\common_header.tex as you like. This can be conveniently done with the fourth contextual menu item. If you are english native, you will probably have to, as at present, this header is set for french-written documents. Of course, this needs some LaTeX knowledge.

This command calls notepad++, if you use another editor, just change corresponding lines in the file 'install.reg', et re-import it into the registry. And don't forget: with LaTeX, to get the summary correct, you need to compile twice.

If you like this trick, you can tell me about, add a comment, or just drop me a line (firstname DOT lastname AT univ-rouen DOT fr).