59

How does one add a LaTeX output* to a question/answer?

*the thing you see in the PDF/DVI when you compile the LaTeX code.

10
  • 1
    Usually you use the standalone class to get a 'focussed' PDF, then convert using a tool of your choice to .png format. Which operating system do you use?
    – Joseph Wright Mod
    Commented Sep 26, 2012 at 10:54
  • You know I was referring to adding an output on a question/answer on tex.SE, right? I'm using Windows 7 but isn't there a tool to do such a thing on tex.SE, i.e. that will be OS-independent?
    – User 17670
    Commented Sep 26, 2012 at 12:02
  • 1
    Compiling a .tex file to output needs a TeX system, and there is not one available via the 'back end'. Moreover, many issues depend on particular versions of packages or similar, and so need to be compiled 'locally' (on a known set up, which a remote server would not be). On Windows, I would use IrfanView to convert the PDF to .png (needs GhostScript installed). There is a question on the main site about this: various approaches are possible.
    – Joseph Wright Mod
    Commented Sep 26, 2012 at 12:13
  • 4
    An easy way to avoid converting the file is to simply make a screenshot of the PDF opened in a PDF reader.
    – raphink
    Commented Sep 26, 2012 at 12:20
  • 1
    Also I'm using this addon for Firefox which also has a standalone version for generic use : addons.mozilla.org/en-US/firefox/addon/lightshot
    – percusse
    Commented Sep 26, 2012 at 12:25
  • 1
    The image hosting site can also take PDFs directly (though the resolution is sometimes not high enough). Commented Sep 26, 2012 at 12:26
  • 2
    there are some possibly useful suggestions in the answers to this question. Commented Sep 26, 2012 at 12:59
  • 2
    Related: how can i upload an image to be included in a question or answer?
    – Werner Mod
    Commented Sep 26, 2012 at 16:08
  • 1
  • Under Windows, the last freeware version of FastStone Capture - v5.3 is very easy to use. It has a built-in editor.
    – Werner Mod
    Commented Dec 21, 2015 at 19:44

10 Answers 10

22

Here's my method, on Windows. Your mileage may vary:

  1. Nothing against it, but I use the "appropriate" document class rather than standalone.

  2. I open the result in my PDF reader, at 100%

  3. I take a screen shot (usually a subrectangle of the whole window), using MWSNAP, and save it (automatically) as a .png for uploading

  4. When, occasionally, the output is too big for a convenient screen capture, my PDF reader, PDFXCHANGE Viewer, allows me to export the .pdf to a number of different graphic formats, at a chosen, appropriate DPI resolution, again for uploading.

8
  • 7
    Windows 7 also has a snipping tool.
    – Werner Mod
    Commented Nov 23, 2012 at 22:22
  • @werner : True. But I've used MWSNAP for years, now. The nice thing I think it has over the MS snipping tool is autosave with a timestamped filename... Commented Nov 24, 2012 at 11:44
  • StackExchange now allows to directly paste to include an image. Perhaps you can add that (it avoids saving to disk and uploading).
    – Werner Mod
    Commented Apr 3, 2013 at 3:20
  • @Werner I must be a bit dumb, because I couldn't make that work. In MwSanp, Edit -> Copy, then in SE Paste doesn't do anything...? Commented Apr 3, 2013 at 10:23
  • You still have to "Insert image..." (or Ctrl G), then paste. Still no luck?
    – Werner Mod
    Commented Apr 3, 2013 at 14:13
  • @Werner No, Ctrl-G just opens a small dialogue (File or Web). Os this a browser catch? I use Firefox. Ah, but do you paste the image, or the image path and filename? Commented Apr 3, 2013 at 19:22
  • You paste the image, not the path. As mentioned, it avoids savings something to disk before uploading. If you can see "(or paste or drag-and-drop)" in your Ctrl-G dialog, then you should be able to paste. If not, then it may be browser dependent. The original release of this features was mentioned in Recent feature changes to Stack Exchange, and references Upload images by drag-and-drop. There seems to be no mention of it being browser-specific, AFAIK.
    – Werner Mod
    Commented Apr 3, 2013 at 19:34
  • In Chrome, the dialogue box includes the word "paste", and you can. In Firefox, it doesn't and you can't. Sorry, I'm not going to buy a 100-Gb-of-RAM PC to be able to run Chrome just for that... Commented Apr 3, 2013 at 19:52
17

My method, on Mac OS X.

Sometimes I use \usepackage[convert,border=2]{standalone}, which requires pdflatex --shell-escape and that ImageMagick is installed (it is if one has a full MacTeX distribution). This has a limitation, because not everything can be obtained just as if a real class were used.

So most of the times I compile the document with the proper class, open the PDF at full screen and take a snapshot with the system tool: Command-Shift-4 allows to choose a rectangle and writes a PNG (72 dpi) on the desktop.

1
  • Just to say this gives sub-optimal results on Linux (with KDE's screenshot tool and kwin_x11) if the target window isn't fully opaque.
    – cfr
    Commented May 7 at 3:09
15

Hopefully my answer below is still useful for you and others, especially for Windows users.

Theory

Once you have had a PDF output, you need to convert it to PNG by using the following batch file named pdf2png.bat. It is convenient to register the batch path to the system variable.

rem pdf2png.bat
echo off
rem %1 PDF filename without extension
rem %2 density
rem %3 alpha, choose one of {on,off,remove}

del "%~1-*.png"

convert -compose copy -bordercolor red -border 3x3 -density %2 -alpha %3 "%~1.pdf" "%~1-%%02d.png" 

Notes:

  • %1 is the first mandatory argument that specifies the filename (without extension) of your PDF to convert.
  • %2 is the second mandatory argument that specifies the density. The higher density makes the PNG dimension larger.
  • %3 is the third mandatory argument that specifies whether or not you preserve the transparency. Use on if you want to preserve the transparency, otherwise choose remove. I don't use off because it produces a lousy output.
  • I added an additional feature such that the output will be enclosed by a red rectangle. If you don't like this feature, remove -compose copy -bordercolor red -border 3x3 from the code above.

Exercise

It is just an example. Your scenario in which you get a PDF might be different from mine. My scenario is as follows: compile the following input file with latex->dvips->ps2pdf to get a PDF output.

% myfilename.tex

\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pst-eucl}
\addtopsstyle{gridstyle}{gridlabels=0}
\begin{document}
\begin{pspicture}[showgrid](4,3)
    \pstGeonode[
        PointName=none,
        PointSymbol={x,none,x},
        dotscale=2]
    (0,0){A}
    (1,3){B}
    (4,1){C}
    \psline(A)(B)(C)
\end{pspicture}
\end{document}

You can invoke the batch from the editor of your choice, but here I invoke the batch from the DOS prompt:

enter image description here

The output is:

enter image description here

The red rectangle is the border produced by -compose copy -bordercolor red -border 3x3.

2
  • I made a duplicate here. Commented Nov 13, 2013 at 18:59
  • For Windows users, the convert alone no longer works. Instead it must be preceded by both magick and a space because convert has a special meaning in Windows. Commented Nov 14, 2018 at 16:25
8

In TeXmaker Cross-platform Editor, Starting from Version 3.4 It is easily possible to export a .png image from the internal pdf viewer with simple right click on the current .pdf page.

Screenshot for .png preparation from .pdf using TeXmaker: Zoom your browser to see closer to code

enter image description here

1
6

ShareX Tool

This tool allows you to quickly capture portions of your screen, automatically uploads the screenshot to imgur.com, then automatically copies the imgur link to your clipboard. All you need to do is press CTRL+V wherever you need it.

Personally, made the hotkeys such that...

  • CTRL+SHIFT+Z: Capture of piece of the screen.
  • ALT+PRTSC: Capture the current window.

You can have the ShareX automatically copy the filepath, the image, the file, etc. It may also be possible to configure ShareX to upload to a specific imgur account automatically.

I use this tool constantly. Cheers~

enter image description here

1
  • 5
    Does this allow use of the correct Imgur account (the paid-for StackExchange one)?
    – Joseph Wright Mod
    Commented Jul 6, 2013 at 5:44
5

Maybe this could be useful for someone: the convert command of ImageMagick has an option which allows you to cut out the written part of an image: -trim +repage.

If you use arara package you may use a rule like this to do the conversion automatically.

For example if you have this myfile.tex (I've setted the background to red only to show the trimming):

% arara: pdflatex
% arara: convert: {background: red, otheroptions: -trim +repage}
\documentclass{book}
\pagenumbering{gobble}
\begin{document}
    Quack
\end{document}

and you run:

arara myfile,tex

you will get this myfile.png:

enter image description here

Of course, you can get the same result if you have myfile.pdf and run:

convert -background red -alpha remove -density 150 -trim +repage "myfile.pdf" -quality 100 "myfile.png"
1
  • What does the -quality do exactly? I've tried to find this out from the documentation, such as I could find, but haven't found it overly informative.
    – cfr
    Commented May 20 at 19:10
5

I wrote a small bash script, that I would like to share here, that converts a LaTeX source to a png image. It runs simple a combination of

  • latexmk for pdf generation,
  • pdftoppm (from the poppler library) for pdf to png conversion,
  • convert (from the ImageMagick suite) for png edge trimming.

By default, it generates a single image from the pdf first page, forcing a \pagestyle{empty} and trimming blank edges. The resolution (in dot per inch) and an additional border (in pixels) could be set through the --resolution and --borderoptions. This is useful, for example, when stackexchange complains about images too small.

If needed, a --multi-pages option allows to generate one image per page.

Here is the full usage:

Usage: textoimg [options] file1 [file2...]

Convert each latex file in input to bitmap images. By default, use only the
first page of the documents and trim edges.

Options :
  -h, --help                  Print this help
  -r, --resolution <value>    Set the resolution in dpi (initial: 300)
  -m, --multi-pages           Generate an image for each page (cancel --trim)
  -t, --trim                  Generate an image from the first page only, trim
                              edges and add a border (cancel --multi-pages)
  -b, --border <value>        Set the border geometry (for the --trim option,
                              use ImageMagick format, initial: 20)
  -c, --border-color <value>  Set the border color (for the --trim option,
                              initial: white)
      --no-color              Turn off color in messaging

and, below the script. Even if it's not very elaborate, I hope it would be useful to someone.

#!/usr/bin/env bash
################################################################################
# textoimg - Convert latex source to bitmap image
# J. Labbé, march 2024
#
# This work is marked with CC0 1.0 (Public Domain Dedication). To view a copy of
# this license, visit http://creativecommons.org/publicdomain/zero/1.0
################################################################################

scriptname=$(basename "${BASH_SOURCE[0]}")

### Shell settings
set -o errtrace -o errexit -o nounset -o pipefail

### Defaults options
resolution=300
trim=true
border_color=white
border=20

### Usage

usage() {
  cat <<EOF
Usage: ${scriptname} [options] file1 [file2...]

Convert each latex file in input to bitmap images. By default, use only the
first page of the documents and trim edges.

Options :
  -h, --help                  Print this help
  -r, --resolution <value>    Set the resolution in dpi (initial: ${resolution})
  -m, --multi-pages           Generate an image for each page (cancel --trim)
  -t, --trim                  Generate an image from the first page only, trim
                              edges and add a border (cancel --multi-pages)
  -b, --border <value>        Set the border geometry (for the --trim option,
                              use ImageMagick format, initial: ${border})
  -c, --border-color <value>  Set the border color (for the --trim option,
                              initial: ${border_color})
      --no-color              Turn off color in messaging
EOF
}

### Messaging

set_colors() {
  if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
    RED='\033[1;31m' GREEN='\033[1;32m' ORANGE='\033[1;33m' BLUE='\033[1;34m'
    PURPLE='\033[1;35m' CYAN='\033[1;36m' YELLOW='\033[1;33m' NOFORMAT='\033[0m'
  else
    RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW='' NOFORMAT=''
  fi
}
set_colors

msg() {
  echo >&2 -e "${1-}"
}

run() {
  local cmd=("$@")
  msg "Running: ${cmd[*]}" && "${cmd[@]}"
}

die() {
  if [[ ${2-1} = 0 ]]; then
    msg "${BLUE}[${scriptname}] ${1-}${NOFORMAT}"
  else
    msg "${RED}[${scriptname}] ${1-}${NOFORMAT}"
  fi
  if [[ ${2-0} -eq 2 ]]; then msg "---" && usage; fi
  exit "${2-1}"
}

### parse options
while true; do
  case "${1-}" in
    -h | --help)
      usage
      exit 0
      ;;
    --debug)
      set -o verbose -o xtrace
      ;;
    --no-color)
      NO_COLOR=true set_colors
      ;;
    -r | --resolution)
      resolution="${2-}"
      shift
      ;;
    -m | --multi-pages)
      trim=false
      ;;
    -t | --trim)
      trim=true
      ;;
    -b | --border)
      border="${2-}"
      shift
      ;;
    -c | --border-color)
      border_color="${2-}"
      shift
      ;;
    -?*)
      die "Error: Unknown option: $1" 2
      ;;
    *)
      break
      ;;
  esac
  shift
done

if [[ $# -eq 0 ]]; then
  die "Error: Missing Filename" 2
fi

### loop on file and process
for file in "$@"; do
  filedir="$(dirname "${file}")"
  filename="$(basename "${file}" ".tex")"

  ## define commands
  latexmk_options=(-gg)
  pdftoppm_options=(-png -r "${resolution}")
  if [[ ${trim} = true ]];then
    latexmk_options+=(-pretex='\AtBeginDocument{\pagestyle{empty}}')
    pdftoppm_options+=(-singlefile)
  fi
  tex_to_pdf_cmd=(latexmk "${latexmk_options[@]}" "${filename}")
  clean_cmd=(latexmk -c "${filename}")
  pdf_to_png_cmd=(pdftoppm "${pdftoppm_options[@]}" "${filename}.pdf" "${filename}")
  trim_png_cmd=(convert -trim -bordercolor "${border_color}" -border "${border}" "${filename}.png" "${filename}.png")

  ## run commands
  msg "${BLUE}[${scriptname}] Generate ${filename}.pdf${NOFORMAT}"
  ( cd "${filedir}" && run "${tex_to_pdf_cmd[@]}" )

  msg "${BLUE}[${scriptname}] Clean LaTeX files${NOFORMAT}"
  ( cd "${filedir}" && run "${clean_cmd[@]}" )

  msg "${BLUE}[${scriptname}] Convert ${filename}.pdf to bitmap image(s)${NOFORMAT}"
  ( cd "${filedir}" && run "${pdf_to_png_cmd[@]}" )

  if [[ ${trim} = true ]]; then
    msg "${BLUE}[${scriptname}] Trim edges from ${filename}.png${NOFORMAT}"
    ( cd "${filedir}" && run "${trim_png_cmd[@]}" )

  ## end message
    die "File ${filedir}/${filename}.png created from ${file}" 0
  else
    die "Files ${filedir}/${filename}-<pagenum>.png created from ${file}" 0
  fi
done
6
  • 1
    Nice script! Thanks for sharing! Commented Apr 19 at 11:58
  • 1
    I actually just tried pdfcrop followed by convert. If I'd remembered about page numbers, it would have been better. Does the extra step in yours serve a specific purpose?
    – cfr
    Commented May 7 at 3:05
  • @cfr I didn't know pdfcrop. In fact, it runs only 2 commands: pdf generation (latexmk) and png conversion (pdftoppm to avoid convert error about security policy). If required, cropping is done with convert. I think the result is the same as the combination latexmk + pdfcrop + convert.
    – jlab
    Commented May 7 at 7:26
  • @jlab For what it's worth, I don't think you need to avoid convert. I've not changed the security policy, I using the same distro as the OP there and convert works fine.
    – cfr
    Commented May 7 at 8:14
  • On the other hand, improving the quality with convert is something I can't get my head around.
    – cfr
    Commented May 20 at 14:38
  • 1
    @cfr As pdftoppm does what I need, I didn't really try to set convert to handle pdf files (although I use it usually for small edit of bitmap).
    – jlab
    Commented May 20 at 19:00
2

In the particular case of a beamer question with overlays, it is often useful to attach the output in the form of an (animated) GIF.

The answer to that (brought to me courtesy of @Schrödinger'scat) is that you can use convert from ImageMagick.org: convert -density <density> -delay <delay> -loop 0 -alpha remove multipage.pdf animated.gif, as explained in this answer.

I'm just adding this here in case someone else is looking for this little piece of magic. :)

0

On OSX, try LaTexIt, which comes with MacTeX.

You will want to copy the essentials of your preamble to the the "document preamble" (which can be made visible by choosing LaTeX->Show preamble).

Then, copy the essentials of what lies between \begin{document} and \end{document} into the main box. (If it is an equation, the best is to copy what lies between the delimiters and select the appropriate environment.)

An image can then be easily exported or copied to the clipboard.

0

0. Starting point:

After compiling the .tex-file you have the .pdf-file.

1. Copy/paste things to/from clipboard

Many .pdf-viewing programs, when displaying a .pdf-file, let you select an area of what is displayed, and copy that to clipboard. Often copying as image is also possible here.

Alternatively many operating systems provide a tool which can be used for making a screenshot of a selected area of the screen, which can as well be an area where a .pdf-viewing-program displays an area of a .pdf-file. (Under Windows, e.g., the so-called snipping-tool.)
With many of these tools the screenshot can either be saved to file (.jpg, .png, .gif) or be copied to clipboard.

On the TeX-LaTeX-StackExchange website the process of embedding an image into a question/an answer is initiated by clicking the symbol enter image description here.
You find this symbol in the tool-bar at the top of the editing-window where you type your question/answer.

When you do that, beneath other options, you are also offered the possibility of pasting an image from the clipboard.

With approaches involving screenshots, the quality of the obtained image also depends on the quality and settings of the hardware in use for displaying.

2. From your .pdf-file via image-conversion-software obtain an image file (.jpg/.png/.gif) and embed that into your question/answer at TeX-LaTeX StackExchange

2.1 Obtaining an image file (.jpg/.png/.gif) suitable for embeddeding into your question/answer at TeX-LaTeX StackExchange

There are countless methods and tools/programs for obtaining .jpg- or .png- or .gif-images for embedding into a question/an answer at TeX-LaTeX StackExchange.

Many programs/methods have already been presented in other answers/comments.

  • Some pdf-viewing-programs let you save selections and/or single pages as .jpg- or .png- or .gif-images.
    With this kind of approach, the image quality depends mainly on the algorithms and settings of the routine used for conversion.

  • With .pdf-viewing-programs that don't offer such functionality you can obtain an image by displaying the .pdf file on the screen by means of the .pdf-viewing-program and then using a tool (e.g., "snipping tool" on more recent MS-Windows platforms) that takes a screenshot of a selected area of the screen and saves that screenshot as an image file in .png or .jpg or .gif format.
    With this kind of approach, the quality of the obtained image also depends on the quality and settings of the hardware in use for displaying.

  • There are also graphics processing programs and command line tools that can convert .pdf files to other file formats, for example .png or .jpg or .gif.

    With this kind of approach, the image quality depends mainly on the algorithms and settings of the programs used for conversion.

2.2 Embedding the image file (.jpg/.png/.gif) into your question/answer at TeX-LaTeX StackExchange

When you have your .jpg-file/.png-file/animated .gif-file, then you can upload it to https://i.sstatic.net/ and thus embed it as an image into your question/answer at TeX-LaTeX StackExchange simply by clicking (on the site of TeX-LaTeX StackExchange) the symbol enter image description here.
You find this symbol in the tool-bar at the top of the editing-window where you type your question/answer.

3. I myself usually go the second way:

I use the program GIMP=GNU Image Manipulation Program to convert .pdf files to other formats. I use GIMP because GIMP is under the GNU license, and because GIMP is available both for Windows and for Linux, so I don't have to get used to multiple/different tools for the two operating systems I use most often.

Both on Linux and on Windows I have GIMP 2.10.8, the GNU Image Manipulation Program, installed.

After compiling the .tex-file you have the .pdf-file.

  • You start GIMP.

  • In GIMP you select "File" → "Open".

  • A dialog-box "Open Image" appears. Here you can browse and select the .pdf-file.

  • Then a window "Import from .pdf" apppears. Here you can select which pages of the .pdf-file you wish to be loaded and whether to load them as single images or to load them as different layers of one single image/animation. Width, height and resolution can be adjusted, too. Then you click "import".

  • Then the Window "Import from .pdf" disappears and the images are loaded into the main window of GIMP.

    1. If (selected) pages were loaded as single images, you can with any of the images do "File" → "Export as" and export it as .jpg- or .png-image. Hereby several dialog boxes appear where you can do several adjustments.

    2. If (selected) pages were loaded as single images, you alternatively can use GIMP's "rectangle select tool" and select an area of one of the images. Via "Edit" → "Copy" you can copy the selected area to clipboard. Via "Edit" → "Paste" → "as new image" you can paste the selected area as a new image. Then you can do "File" → "Export as" and export the new image containing only the selected area as .jpg- or .png-image. Hereby several dialog boxes appear where you can do several adjustments.

    3. If (selected) pages were loaded as layers of one single image/animation, then at the top of the right side of GIMP's window you find a list with the names/numbers of the different frames.
      The frame whose name/number is listed at the bottom of the list will be displayed as the first one. The frame whose name/number is listed at the top of the list will be displayed as the last one.
      In that list you can left-click names/numbers of single frames and while holding the left mouse-button move the corresponding list-entry upwards or downwards in order to change the order of the elements of the list and thus the order in which frames will be displayed.
      In that list you also can select/right-click the name of a single frame. Then a context-menu opens up where you can do adjustments to the properties of the frame in question.
      E.g., you can append to the name/number of a frame something like (1250ms) to specify that the frame in question will be displayed for 1250 milliseconds.
      There also is "Filters" → "Animation" → "Optimize (for GIF)" / "Optimize (Difference)".
      There also is "Filters" → "Animation" → "Playback" for watching the animation.
      When everything is according to your wishes you can do "File" → "Export as", select "file type: gif" and save the thing as an animated .gif-file.

E.g., compiling the following MWE

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\scalebox{10}{\Huge{A}}
\newpage
\scalebox{10}{\Huge{B}}
\newpage
\scalebox{10}{\Huge{C}}
\end{document}

yields a .pdf-file from which via GIMP you can derive an animated .gif-file where pages are displayed one by one:

enter image description here

1
  • 2
    on windows for non-animated things I simply use the snippet tool it provides. I don't even need to save them, they are in the clipboard and can be added with ctrl+v while writing an answer. Commented Jun 8, 2021 at 9:45

You must log in to answer this question.

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