79

My document structure has

  • one file with preamble (i.e. MainTex)
  • and around 75 individual .tex files (i.e. Chapter_01, Chapter_02, ..., Chapter_75) representing each chapter.

I am using \include command to create a one big PDF file, the output is MainTex.pdf. Life is all good up to this point.

If I have to create individual PDF for each chapter then do I need to run 75 times with each chapter name and rename the PDF manually to match to chapter name. Because if I include only Chapter_01 and run it creates PDF named as MainTex.pdf.

Is there a way I can automate this workflow?

3
  • 2
    Not an automatic solution, but the program pdfsam allows one to split a PDF based on the bookmark levels of the PDF, so if you use the hyperref package, that is perhaps less work. Commented Oct 12, 2011 at 14:41
  • 2
    Not automated here either, and very inelegant, but better than compiling and modifying 75 times: what about simply splitting the resulting pdf file, ignoring its origin? For instance, in Mac OS X's Preview you can simply "print" on a new pdf file a range of pages from an existing file. Not so helpful, perhaps...
    – DaG
    Commented Oct 12, 2011 at 15:46
  • See also tex.stackexchange.com/questions/5228/… Commented Oct 12, 2011 at 16:51

9 Answers 9

84

Suppose your main file is maintex.tex:

\documentclass[a4paper]{book}
\begin{document}
\include{chap01}
\include{chap02}
\include{chap03}
\end{document}

Then you can compile only chapter 1 by calling, from the command line

pdflatex -jobname=thechap01 "\includeonly{chap01}\input{maintex}"

In order to do all at once, the command might be (bash shell)

for i in chap*.tex; do j=${i%.tex}; pdflatex -jobname=the$j "\includeonly{$j}\input{maintex}"; done

It's necessary to change the output file name from chap01 to something different, because otherwise the reading of the .aux file would lead to an infinite loop. It's easy to rename the obtained PDF files afterwards (or in the same command, by adding ; mv the$j.pdf $j.pdf before done).

11
  • 1
    @awesome it worked great, all I had to do was to replace pdflatex to xelatex. I did not have to rename the files, it did not go into infinite loop.
    – Aku
    Commented Oct 16, 2011 at 0:41
  • 3
    Is invoking pdflatex once per chapter enough? Commented Jan 1, 2012 at 15:49
  • 5
    @CounterTerrorist This should be performed when the "big" document has already resolved all cross-references, so one run is sufficient.
    – egreg
    Commented Jan 1, 2012 at 15:53
  • 1
    This works very well but seems to be missing the bibtex references. I built the main file separately to get the references working but split chapters have ?s.
    – recluze
    Commented Jan 26, 2012 at 3:45
  • 1
    @vonbrand Just \include also the frontmatter.
    – egreg
    Commented Nov 13, 2018 at 18:07
23

Yes, this workflow is supported, but it has to be performed from the start, rather than after the fact. Here's what I mean by that.

The subfiles package provides the means to actually have individual sub files that are included in your main .tex file (using \include or \includeonly) but also are compilable themselves. The package should be included in the main .tex, while each subfile has a working preamble. You can then iterate (loop) over the respective subfiles (chapters in your case) using a standard bash script, and compile each chapter using latex, pdflatex or xelatex. For example, under DOS, the following should work:

for /f %%a IN ('dir /b Chapter_??.tex') do call pdflatex %%a

You may have to run this entire script at least two times for references in each chapter to work.

The standalone document class provides a similar functionality, skipping preambles of included files and only considering content contained within the document environment when compiling the main .tex. Included files, however are individually compilable.

The main drawback from compiling this way is referencing across chapters and page numbers that will restart at 1 for each chapter. The former might be addressed using the xr package, while the latter may be addessed by inserting the respective page number modification in the document preamble (via \setcounter{page}{...}), perhaps even reading it from the main .aux file. Regardless, this fiddling may be difficult to master if not set up properly.

2
  • Sorry for bothering you on such an old post. I am using this strategy with a thesis project using yathesis document class. I have followed the instruction of subfiles documentation but oddly when I compile the subordinate files, although the compilation doesn't show any problem, no pdf generated. I am referred instead to the main document pdf. I think the problem is inherited from the limitation that the subordinate files take their preamble (including document class) from the main file. Btw, do you know a way to change that? Commented Dec 10, 2017 at 19:42
  • @AymaneFihadi: It's difficult to say what you could be doing differently. In some editors (TeXnicCenter, for example), you can compile the entire document with a click of a single button, or compile the actively open .tex with the click of a different button.
    – Werner
    Commented Dec 12, 2017 at 16:22
15

Here's a way that uses the fabulous arara tool to implement @egreg's solution

main.tex

% arara: makechapters: {items: [lions, zebras]}

\documentclass{report}

\begin{document}

\include{lions}
\include{zebras}

\end{document}

When you call

arara main.tex

you will get lions.pdf and zebras.pdf. You can list any number of chapter files in the items argument, and you can also choose to set compileAll: off if you don't want to compile main.tex first. The default is compileAll: on, and I'd recommend only turning it off if you are 100% sure that the necessary .aux files are up to date.

For a big document, it'll take a while, but it's the kind of thing that you set running before stepping away from your desk for a bit.

makechapters.yaml

!config
# Make chapter files rule for arara
# author: Chris Hughes
# last edited by: cmh, May 20th 2013
# http://tex.stackexchange.com/questions/31334/how-to-create-individual-chapter-pdfs
# requires arara 3.0+
#
# Sample usage: Assume you have the following directives in main.tex, with chapter files
#               lions.tex, zebras.tex
#
# % arara: makechapters: {items: [lions]}
# % arara: makechapters: {items: [lions, zebras]}
# % arara: makechapters: {items: [lions, zebras], compileAll: no}
# % arara: makechapters: {items: [lions, zebras], compileAll: yes}
#
# which will create lions.pdf, zebras.pdf
#
# Note that, by default, this compiles main.tex first so that all of the necessary .aux
# files are generated- this is vital for cross referencing to work, particularly in 
# the case of a *forward* cross reference (e.g chapter 2 refers to chapter 3). 
#
# If you set compileAll to false/no/off, then it will *not* compile the main file
# first- be careful with this one, as the necessary .aux files may not be present, and 
# your cross references may break. 
identifier: makechapters
name: MakeChapters
commands: 
- <arara> @{ isTrue( compileAll, engine.concat(' "').concat(file).concat('"') )}
- <arara> @{engine} -jobname=tmpCMH "\includeonly{@{item}}\input{@{file}}" 
- <arara> @{engine} -jobname=tmpCMH "\includeonly{@{item}}\input{@{file}}" 
- <arara> @{ isWindows( "cmd /c move", "mv" ) } tmpCMH.pdf @{item}.pdf
arguments:
- identifier: engine
  flag: <arara> @{parameters.engine}
  default: pdflatex
- identifier: compileAll
  flag: <arara> @{parameters.compileAll}
  default: true
2
  • This looks great but when I run it I get the error below. Any guesses? -- I have spotted an error in rule 'makechapters' located at /path/. I could not parse the rule, something bad happened. This part is quite tricky, since it involves aspects of the underlying data serialization format. I will do my best to help you in any way I can. There are more details available on this exception: DETAILS --------------------------------------------------------- com.charleskorn.kaml.IncorrectTypeException: Expected an object, but got a scalar value Commented Sep 9, 2020 at 19:00
  • 1
    This answer was posted a few years ago, and stars has moved on since then. Perhaps a question to the repository: github.com/cereda/arara
    – cmhughes
    Commented Sep 9, 2020 at 20:17
9

I wrote a bunch on the standalone package, and then saw Werner beat me too it. Ah well!

As an aside, I use Chris Monson's Ultimate LaTeX Makefile to build documents. If you have a UNIX system (or cygwin), it just works. For example, you could type "make Chapter_01" (to use your file name) and it would produce a nice PDF with correct references, etc.

However, its best feature is automatic dependency tracking. It would be able to determine that your main file depends on the 50+ chapter files, and it will recompile as necessary. This is great if you are tweaking a chapter but building the entire document.

It even takes care of running latex and biblatex enough times to get everything working right!

5

I'm experimenting with the following approach. Let the master file contain this:

\documentclass{...}
\usepackage{newclude}
\def\inmaster{1}
\ifdefined\subonly\includeonly{\subonly}\fi
\begin{document}

\include{subone}
\include{subtwo}

\end{document}

and the subfiles begin like this (no preamble or \begin{document}):

\ifdefined\inmaster\else\def\subonly{\jobname}\input{master}\fi

\chapter{Chapter Name}
...

Finally, make all the .aux files symbolically linked, e.g. with the bash command

for f in *.tex; do ln -s master.aux ${f%.tex}.aux; done

Now the master file can be compiled on its own to produce output containing all the chapters, and likewise each individual chapter file can be compiled on their own to produce output containing only that chapter (but which will still be correctly numbered and can refer to labels in other chapters).

This has the advantage that once it's set up, each .tex file can be compiled just like normal; no fancy makefiles, scripts, or compilation tools are required. However, it has the disadvantage of requiring the initial setup of symbolic links (and in particular of requiring an OS that supports them). But one can trade-off the symbolic links for a slightly more complicated compilation, compiling each chapter file with e.g.

cp master.aux chapterone.aux && pdflatex chapterone

Either way, a script could easily loop over the chapter files and compile them all.

2
  • I really like this solution! However, I'm trying to use it for an article, where I'd really like to get rid of the clearpages before and after the include. Thus, I tried using the starred version from newclude, but somehow, that messes up the section numbering in the standalone files after the first. Any ideas for a fix? Commented Sep 23, 2014 at 14:18
  • 1
    Ah: It seems this is simply a bug in newclude: That includeonly doesn't work properly with the starred include. I guess I'll just have to find a way around that. Commented Sep 23, 2014 at 17:27
3

I know this is an old question, but here is an alternative approach, based on an idea from Automatically create two PDF output files from one tex file [duplicate] (accidentally I have posted the answer at Can one TeX file output to multiple PDF files?first)

The idea is to write at begin of each chapter some commands (including the page numbers where to split the pdf) in a batch-file and after LaTex has finished, run the script to split the pdf into multiple files (using pdftk).

\documentclass[10pt,a4paper]{report}
\usepackage[latin1]{inputenc}
\usepackage{pageslts} %  theCurrentPage
\usepackage{calc} % theCurrentPage+1
\usepackage{blindtext} % Lorem ipsum dolor ...

\newcounter{FirstPage} % counter, for first page number
\setcounter{FirstPage}{1} % Set FirstPage to page 1

\newwrite\BatchFile% Batch-Datei
\immediate\openout\BatchFile=BatchFile.txt% *.bat don't work

\newcommand{\Split}[1]{%
\immediate\write\BatchFile{pdftk.exe\space \jobname.pdf\space cat \theFirstPage -\theCurrentPage\space output\space \jobname-#1.pdf dont_ask}% 
\setcounter{FirstPage}{\theCurrentPage+1}% set FirstPage to new first page
}
\begin{document}
\pagenumbering{arabic} % for pageslts

\chapter{One}

\Blindtext 

\Split{C1} % Split for Chapter 1  
%--------------------------------------------------------------
\chapter{Two}

\Blindtext\Blindtext

\Split{C2} % Split for Chapter 2
%--------------------------------------------------------------
\chapter{Three}
\setcounter{page}{1} % Chapter 3 with new page numbers

\Blindtext \Blindtext \blindtext 

\Split{C3} % Split for Chapter 3
%==========================
\immediate\write\BatchFile{exit}% 
\immediate\closeout\BatchFile% 
\immediate\write18{cmd /c move BatchFile.txt BatchFile.bat} % rename Batch File
\end{document}

I know the solution can be improved, for example merge the \Split with the \chapter command or do the stuff at the end automatically.

1
  • I do something like this in some of my code where my analogue of your \Split commands are section commands that generate predefined labels in the aux file. A python script then extracts the labels from the aux file and uses this information to break up the pdf file. It works very well.
    – user30471
    Commented May 6, 2015 at 7:42
2

I have a similar workflow, and what I do is only semi-automatic, but it's enough for my use case. After I read this post, I wrote a simple (and funny, I guess) LaTeX template for doing this. (It might not be useful for you, since one has to know the pagenumbers, but it is still more comfortable for me than pdfsam or "print to file" solutions.)

2

I like egreg solution a lot, and I have enhanced it a bit.

I created a Makefile that I modified to:

  • compile and run bibtex so that all references are correct
  • compile only the chapters that I need.

Here it goes:

SRC = main
DST = book.pdf
LATEX = pdflatex
FLAGSLATEX = -interaction=batchmode
BIBTEX = bibtex
FLAGSBIB = -terse
INDEX = makeindex

${DST} : aux biblio toc index
        ${LATEX} ${FLAGSLATEX} ${SRC}.tex -jobname=${DST}

aux : ${SRC}.tex
        ${LATEX} ${FLAGSLATEX} ${SRC}.tex

toc : biblio aux
        ${LATEX} ${FLAGSLATEX} ${SRC}.tex

biblio : aux
        ${BIBTEX} ${FLAGSBIB} ${SRC}

index : aux
        ${INDEX} ${SRC}

%.aux : aux %.tex
        ${LATEX} ${FLAGSLATEX} -jobname=the_$* "\includeonly{$*} \input{${SRC}}"

%.bib : %.aux
        ${BIBTEX} ${FLAGSBIB} the_$*
        ${LATEX} ${FLAGSLATEX} -jobname=the_$* "\includeonly{$*}\input{${SRC}}"

%.pdf : %.bib
        ${LATEX} ${FLAGSLATEX} -jobname=the_$* "\includeonly{$*}\input{${SRC}}"

clean: 
        @rm -f *.log *.aux *.dvi *.toc *.lot *.lof *.bbl *.ind *.mtc* *.blg *.idx *.ilg *.maf *.tdo *.gm main.pdf

Then when you run 'make' it compiles the whole document, and when you run 'make Chapter_01.pdf' it compiles the first chapter. You can also add a command in the Makefile to compile all the chapters independently, like:

chapters : ${DST}
        for i in chap_*.tex; do ${LATEX} ${FLAGSLATEX} -jobname=chap_$$i "\includeonly{chap_$$i}\input{${SRC}}"; done
0

See my reply at Extract document statistics? - How many pages has chapter xy? Count fixmes?: python script which extracts chapters/sections/... from .toc file and splits the final PDF.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .