[Tex/LaTex] Minimize automatically the page size of the PDF outputs

marginspdf

I would like to produce the PDF version of the following TEX code without margins. How can I achieve this automaticcaly, even if it needs tricky code (I'm a regular user of Python) ?

I would like to that so as to show examples of small LaTeX codes without wasting storing spaces on my web site.

\documentclass[10pt,a4paper]{article}
    \usepackage[utf8x]{inputenc}
    \usepackage{ucs}
    \usepackage{amsmath}
    \usepackage{amsfonts}
    \usepackage{amssymb}


\begin{document}

\section{One document to display}

How to produce an output without any margin.

\noindent
$ E = m c^2 $ but it seems that we can have $ v > c $.

\end{document}

Best Answer

I would recommend you use the varwidth package which is similar to the minipage environment, but sets its width to match the narrower natural width based on the content.

This can be used either with the standalone package, or you can directly use the preview package to get (note that the border shown here is from my image capturing):

enter image description here

Here is the MWE using the standalone class:

\documentclass[tightpage]{standalone}
\usepackage{varwidth}
\begin{document}
\begin{varwidth}{\linewidth}
\section{One document to display}

How to produce an output without any margin.

\par\noindent
$ E = m c^2 $ but it seems that we can have $ v > c $.
\end{varwidth}

and using the preview package:

\documentclass{article}
\usepackage[active,tightpage]{preview}
\usepackage{varwidth}
\begin{document}
\begin{preview}
\begin{varwidth}{\linewidth}
\section{One document to display}

How to produce an output without any margin.

\par\noindent
$ E = m c^2 $ but it seems that we can have $ v > c $.
\end{varwidth}
\end{preview}
\end{document}

I suspect that standalone class internally uses the preview package to do something like this, so probably not much difference in this case, but might be useful if you needed to use a different class.


If this is something you are going to do often it is worthwhile automating this solution by using \AtBeginDocument and \AtEndDocument in the preamble to automate this. Here is the same code with this automation in the preamble and using the book class:

\documentclass{book}
\usepackage[active,tightpage]{preview}
\usepackage{varwidth}
\AtBeginDocument{\begin{preview}\begin{varwidth}{\linewidth}}
\AtEndDocument{\end{varwidth}\end{preview}}

\begin{document}
\section{One document to display}

How to produce an output without any margin.

\par\noindent
$ E = m c^2 $ but it seems that we can have $ v > c $.
\end{document}