[Tex/LaTex] pdfcrop fails to crop a PDF document with non-white background

pdfcrop

I have a PDF document created from the following input file.

\documentclass[cmyk,a4paper]{minimal}
\usepackage{geometry,xcolor}
\pagecolor{cyan}
\parindent=0bp

\begin{document}
\fbox{$\displaystyle E=mc^2$}
\end{document}

But it cannot be cropped by pdfcrop because of the non-white background. I think the non-white background has affected the bounding box. So how to fix this isssue?

Confirmation

The pdfcrop author said in Martin's and Lev's reports as follows:

The PDF format does not know a "page color". pdftex.def implements it
by putting a colored box as first thing on the page. Thus it is not
quite clear for a program what kind of boxes are valuable content and
what could be cropped.

To get a properly cropped image, you can run the TeX document without
\pagecolor and run gs -sDEVICE=bbox -dBATCH -dNOPAUSE test.pdf to
get the bounding box data. It you are using hyperref, you can use the
Bounding Box data for option pdfpagescrop. Or run pdfcrop with option
–box and the Bounding Box data.

— Heiko Oberdiek

Best Answer

I would do it another way around: (This might actually solve some other issues of you)

Place the whole thing in a savebox in the preamble. (You have to manually enable the normal font use \normalfont for this AFAIK.) Then you can measure the dimensions of the box and set the page dimensions accordantly. This will give you a PDF or PS which already has to correct size. For larger content I recommend to use a minipage wrapper as usual.

The \pagecolor command still works here. I would have thought you manually need to place a colored rectangle (\rule) with the same size behind the content.

The following works for me using pdflatex (PDF), latex->dvips1 (PS), latex->dvips1->ps2pdf (PDF), xelatex and lualatex and produces a correctly sized file.

1 without any options, no -E required

\documentclass{article}
\usepackage[cmyk]{xcolor}
\pagecolor{cyan}
\pagestyle{empty}
\parindent=0bp

\begin{lrbox}{0}%
    \normalfont
    \fbox{$\displaystyle E=mc^2 $}%
\end{lrbox}

\sbox0{\raise\dp0\box0}% raise box so it is all height, no depth
%\sbox0{\rlap{\textcolor{cyan}{\rule{\wd0}{\ht0}}}\box0}% \pagecolor surprisingly works so this is not needed

\usepackage[noheadfoot,nomarginpar,margin=0pt,paperwidth=\wd0,paperheight=\ht0]{geometry}

\begin{document}
\box0
\end{document}

Result