I'd like to change the background color and text color programmatically in PDF documents so that they're nicer to read at night (kinda like in Adobe Reader: Edit -> Preferences -> Accessibility -> Replace Document Colors).
Is there any good command line tool or API for Windows that can do that?
So far I haven't found any. It's OK if it needs to save the newly colored PDF into a new file.
There is no way to do this directly, with no (Free Software or gratis) tool I'm aware of. (Because in the general case, you'll have to change all colors of the PDF pages, not just the background alone, so you can still have some contrast and color differences.)
What you describe for Adobe Reader does not change the PDF file itself, it changes the way the application renders the pages (by inverting colors, or similar). The PDF remains the same during and after viewing it.
However, you might be able to achieve a similar thing by applying a suitable ICC color profile to the input PDF and produce, with the help of (a very recent version of) Ghostscript, a new output PDF from this.
The question would remain: what IS a "suitable" ICC color profil for your purpose??
I've shortly considered to apply a gray-ish background to the PDF with the help of
pdftk ... background ...
command line. But this would probably make some or many PDFs unreadable. (A black background would surely make it unreadable, because most text is black and would remain so.)To create a PDF page (A4 size) which could serve as the gray background, you could use Ghostscript:
gs -o gray.pdf -sDEVICE=pdfwrite -g5950x8420 -c ".8 setgray 0 0 595 842 rectfill showpage"
.Then apply it to your original PDF (A4):
pdftk original.pdf background gray.pdf output orig-with-backgr.pdf
.Note, this will only change the background of these pages (or those areas of pages), where the original background is transparent, as most text-based PDFs are. It will not work for pages or areas where the background is opaque white or color.)
You can also achieve a permanent color change (inverse colors) quite easily with the help of ImageMagick. But this will at the same time munch and make mincemeat of your nice vector PDFs, converting them into complete-raster image pages:
convert nice.pdf -alpha off -invert inverted-colors-ugly-raster.pdf
.
Finally, here is a rather unreliable way to accomplish the inverting of colors with the help of Ghostscript. It sets up a colortransfer function for the output PDF file:
gs -o output.pdf \
-sDEVICE=pdfwrite \
-c "{1 exch sub}{1 exch sub}{1 exch sub}{1 exch sub} setcolortransfer" \
-f input.pdf
It is unreliable, because not every PDF viewer will honor that setting. I've tested it a few times in the past...
These viewers DO SHOW inverted colors:
These ones DON'T SHOW inverted colors: