4

Is it possible to compile a tex file with command line arguments passed to the tex file? For example, a tex file merge.tex

\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf[pages=-,fitpaper]{1.pdf}
\includepdf[pages=-,fitpaper]{2.pdf}
\end{document}

I want to be able to use this like a shell command, where I can specify any two pdf files to replace 1.pdf and 2.pdf at each compilation of the tex file, something like pdflatex merge.tex first.pdf second.pdf.

Thanks.

Tim
  • 5,763
  • You can create a shell script with 2 arguments. You call this script and pass two pdf files and the script will take each one and copy them to the same source pdf file, for example, first.pdf and second.pdf. Then you include always those pdf files in your tex file and finally the script runs pdflatex merge.tex. – Sigur May 08 '15 at 15:01
  • You could use a shell environment variable which is evaluated during compilation, see a (different example) here: http://tex.stackexchange.com/questions/184923/how-to-include-a-second-file-only-if-environment-variable-is-set –  May 08 '15 at 15:04

1 Answers1

8

merge.tex

\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf[pages=-,fitpaper]{\filea.pdf}
\includepdf[pages=-,fitpaper]{\fileb.pdf}
\end{document}

Then a command line of

pdflatex '\def\filea{myfile1}\def\fileb{myfile2}\input merge'

Should do as you ask.

Depending on which system commandline you use, you may need different quote ' or to double the \ to \\

David Carlisle
  • 757,742
  • What a simple command?! Nice! – Sigur May 08 '15 at 16:15
  • thanks. what if merge.tex isn't stored in the current directory? – Tim May 08 '15 at 16:40
  • @Tim well if it's somewhere where pdflatex merge works, that will work, or you can put the full path after the \input just as you can (but probably shouldn't) do pdflatex a/b/c/merge – David Carlisle May 08 '15 at 16:42
  • put the pathname of merge.tex into $PATH of Ubuntu doesnt' work, does it? – Tim May 08 '15 at 16:44
  • @Tim merge.tex isn't a command so PATH isn't relevant it can be in any directory in the tex input path, just as latex packages, TEXINPUTS, specified as an environment variable , or more normally in the texmf.cnf file. – David Carlisle May 08 '15 at 20:34
  • @DavidCarlisle, if myfile1 is passed to a script and stored in variable $myfile, how to call pdflatex? I guess that \def\filea{$myfile1} will not work, will? – Sigur Aug 22 '15 at 11:39
  • @Sigur it depends on your shell, but if you use " rather than ' then the shell should expand $myfile but you may need \\ and \{ for \ and { – David Carlisle Aug 22 '15 at 11:44
  • @DavidCarlisle, let me try. Thanks. By the way, I use bash. – Sigur Aug 22 '15 at 11:46