Search code examples
pdfluapandocxelatex

How to remove Linebreak or SoftBreak after an Image in .md to PDF in Pandoc


I have a .md file with below content. some images have LineBreak or SoftBreak after image like as below:

![sample.PNG](/.attachments/sample.PNG =516x434) *Figure: Premises tab*

and some image files doesn't have LineBreak or SoftBreak after image:

![sample2.PNG](/.attachments/sample2.PNG =516x434)

I am using Image function in lua script to add Linebreak after every image:

function Image (img)
  -- remove leading slash from image paths
  img.src = img.src:gsub('^/', '')

  -- find the index and values for the size definition and apply them to the image
  idx, _, width, height  = string.find(img.src, "%%20=([%d]*)x([%d]*)")

  if (idx ~= nil) then
    img.src = string.sub(img.src, 1, idx - 1)
  end
  return {
    pandoc.RawInline('latex', '\\hfill\\break{\\centering'),
    img,
    pandoc.RawInline('latex', '\\par}')
  }
end

When I run the below pandoc command. It throws error and doesn't generate the PDF file.

pandoc test.md -V geometry:margin=1in -H header.tex -o PDFs\test.pdf --lua-filter pdf-filters.lua --pdf-engine=xelatex -V fontsize=9pt -V colorlinks=true  -V linkcolor=blue

Here is the error which throws when run the above command.

Error producing PDF.
! LaTeX Error: There's no line here to end.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.243 \emph

How to generate PDF file with line break after every image. Thanks for helping!


Solution

  • I have fixed this issue by check if the image is the last element in the current paragraph. Here is the lua Image function:

    function Image (img)
      -- remove leading slash from image paths
      img.src = img.src:gsub('^/', '')
    
      -- find the index and values for the size definition and apply them to the image
      idx, _, _, _  = string.find(img.src, "%%20=([%d]*)x([%d]*)")
    
      if (idx ~= nil) then
        img.src = string.sub(img.src, 1, idx - 1)
      end
    
      -- check if the image is the last element in the current paragraph
      local last_in_paragraph = false
      local parent = img
      while (parent and not last_in_paragraph) do
        parent = parent.parent
        if (parent and parent._type == "Para") then
          local last_child = parent.content[#parent.content]
          if (last_child == img) then
            last_in_paragraph = true
          end
        end
      end
    
      -- add a line break or new paragraph depending on whether the image is the last element in the current paragraph
      if (last_in_paragraph) then
        return {
          pandoc.RawInline('latex', '\\hfill\\break{\\centering'),
          img,
          pandoc.RawInline('latex', '\\par}')
        }
      else
        return {
          pandoc.RawInline('latex', '\\hfill\\break{\\centering'),
          img,
          pandoc.RawInline('latex', '}')
        }
      end
    end