Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pandoc as a library to make a PDF

Tags:

haskell

pandoc

Part of a project I am working on involves creating a PDF, using Pandoc. I have the part of the program which makes a PDF. To figure out how to do this, I am trying to modify fuel.hs from JGM BayHack 2014.

However, I am having difficulty. I have the following function:

export :: (MonadIO m) => Pandoc -> m (Either BL.ByteString BL.ByteString)
export = liftIO . makePDF "xelatex" writeLaTeX  def { writerStandalone = True } 

In the body of my modified fuel.hs,

  pdfbytes <- export letter
  print pdfbytes

I get the following output:

$ stack runghc fuel.hs
Run from outside a project, using implicit global project config
Using resolver: lts-3.7 from implicit global project's config file: /home/stevejb/.stack/global/stack.yaml
Left "! Emergency stop.\n<*> /tmp/tex2pdf.8283/input.tex\n                               \nNo pages of output.\nTranscript written on /tmp/tex2pdf.8283/input.log.\n"
"Fail"

However, the log file that is being referenced does not exist. I am not sure how to debug this. I have xelatex installed.


like image 219
stevejb Avatar asked Jan 06 '23 22:01

stevejb


1 Answers

With great help from #haskell IRC, I was able to get it working. The key was to add my own LaTeX template. Thus, one can use the following:

export :: (MonadIO m) => String ->  Pandoc -> m (Either BL.ByteString BL.ByteString)
export tmpl pdoc = liftIO $ makePDF "xelatex" writeLaTeX (def { writerStandalone = True, writerTemplate = tmpl}) pdoc

getLetter  = do
  json <- BL.readFile "cng_fuel_chicago.json"
  let letter = case decode json of
                    Just stations -> createLetter [s | s <- stations,
                                        "Voyager" `elem` cardsAccepted s]
                    Nothing       -> error "Could not decode JSON"
  return $ letter


main :: IO ()
main = do
  letter <- getLetter
  temp <- readFile "template.tex"
  let str_should_have_something = writeLaTeX (def {writerStandalone = True, writerTemplate = temp}) letter
  print str_should_have_something
  mybytes <- export temp letter

  case mybytes of Right b -> BL.writeFile "mypdf.pdf" b
                  Left  _ -> putStrLn "Export error"

To get a template, you can use Pandoc in standalone mode from the shell:

pandoc -D latex > template.tex

Also, there may be an issue with Pandoc installed using stack, using cabal, and using the system package manger, in terms of finding the default templates. I am not sure exactly how all of this interacts.


Fully contained gist here.

like image 146
stevejb Avatar answered Jan 15 '23 07:01

stevejb