I'm trying to generate a pdf file containing an algorithm, which will be included in the main document as a figure. I tried using standalone as follows:
% main.tex
\documentclass{standalone}
\usepackage{algorithm2e}
\begin{document}
\begin{algorithm}
$x \gets 0$\;
\If{$x < 10$}{
$x \gets x + 1$\;
}
\end{algorithm}
\end{document}
Above example gives multiple errors when compiling and fails to generate a proper layout. I tried a few options for standalone
(e.g. preview
and varwidth
) but failed to make it work. There is a similar question (using standalone with algorithmicx or algorithm2e) but it is rather old and does not have a proper answer. I already have my algorithms written in algorithm2e so I would rather not use a different algorithm package. I simply need a working example for this.
Best Answer
The algorithms are set in a floating environment, whereas
standalone
puts the contents in a box. This is incompatible.However, if you give the algorithm the
[H]
option, it will no longer be floating, so you can use it. It will no longer have the possibility to have a caption, unless you use thecapt-of
orcaption
package, but you probably will put the captions in your main document.Note that it will not be possible to have the algorithms cropped to their minimal horizontal space, because the
algorithm
package will put them in several layers of boxes, some of them with explicit width\hsize
. But I guess you want all of them to be the same width, and you can just set\hsize
to the desired width.But if you need the algorithms in another document, framed and with figure captions, why don't you just put them there and use the
figure,boxed
options?This makes them float (it uses a real
figure
environment, so they may end up at a different location, as all floats. You can prevent that by using\usepackage{float}
, and then\begin{algorithm}[H]
. However, this may cause undesired white space on the page if the algorithm doesn't fit.You can also remove the
figure
option; then thealgorithm
environment has a[H]
option, that makes the algorithm non-floating. But then you must add a caption with thecaption-of
orcaption
package. In this case the caption will be placed outside the box, however.