我试图在生成 pdf 文件时记录字形节点的位置,但调用 pdf.getpos() 函数时总是得到 0 值。我该如何修复它?这是我的代码,输出记录在输出文件“test.txt”中。
\documentclass{article}
\usepackage{luacode,luatexbase}
\usepackage[letterpaper,left=1in,right=1in,top=1in,bottom=1in]{geometry}
\begin{document}
\begin{luacode*}
local GLYPH_ID = node.id("glyph")
function getposition(head)
while head do
if head.id == 0 or head.id == 1 then
getposition(head.list)
elseif head.id == GLYPH_ID then
local savepos = node.new("whatsit","save_pos")
local h,v = pdf.getpos()
file = io.open("test.txt", "a")
file:write(tostring(h), " ", tostring(v),"\n")
file:close()
end
head = head.next
end
return true
end
luatexbase.add_to_callback("post_linebreak_filter",getposition,"getposition")
\end{luacode*}
My \emph{text} should be here and it can be really long so the lines can break but I still need to get position of glyph nodes.
\end{document}
答案1
关注此处的评论https://tex.stackexchange.com/a/591608/249348,答案如下((TeX Live 2021) (format=lualatex 2021.8.18)):
\documentclass{scrbook}
\usepackage{fontspec}
\usepackage{luacode}
\setmainfont{Libertinus Serif}
\begin{luacode}
function PrintPos()
local x,y = pdf.getpos()
file = io.open("test.txt", "a")
file:write(x," ",y,"\string\n")
file:close()
end
function ProcessList(head)
for n in node.traverse(head) do
if node.is_glyph(n) then
local printpos = node.new("whatsit","late_lua")
printpos.data = PrintPos
node.insert_after(head, n, printpos)
end
if n.head ~= nil then
ProcessList(n.head)
end
end
end
function PrintCoordinates()
local soBox = tex.getbox("ShipoutBox")
ProcessList(soBox)
end
\end{luacode}
\AddToHook{shipout/before}{\directlua{PrintCoordinates()}}
\begin{document}
My \emph{text} should be here and it can be really long so the lines can break but I still need to get position of glyph nodes.
\end{document}