[Tex/LaTex] Adding an image in luatex

graphicsluatex

I would like to use Lua functions in order to reproduce the effect of \includegraphics{testimg}. This means that the image "testimg.pdf"
would appear centered in the following example.

\documentclass{minimal}
\begin{document}
\centering

Some text.

\directlua{
  tex.print("Text from Lua.")
  a = img.new({filename="testimg.pdf", height="200bp"})
  img.write(a)
}

Some more text.

\end{document}

While the text does indeed appear centered, the image appears at the left of the page. Clearly, I am doing something wrong. Any hints?

Best Answer

What you do with img.write() is to write the node directly into the output stream without any knowledge of the current state (the \centering). When you are inside a horizontal everything is fine. When you are in vertical mode, the node just gets insert into the stream, that is

enter image description here

The hlists all have a leftskip and a rightskip (for the \centering) and the image has none. You have to insert the leftskip and the rightskip yourself.

If you have graphviz installed, you can try the viznodelist (https://gist.github.com/pgundlach/556247) lua file to generate a gv file from the page:

\usepackage{atbegshi}
...
\AtBeginShipout{%
  \directlua{
     require("viznodelist")
     viznodelist.nodelist_visualize(tex.box["AtBeginShipoutBox"],"nodes.gv")
  }}

and look at the resulting file nodes.gv.

Related Question