1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{- |
Module : Text.Pandoc.PDF
Copyright : Copyright (C) 2012-2020 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of LaTeX documents to PDF.
-}
module Text.Pandoc.PDF ( makePDF ) where
import qualified Codec.Picture as JP
import qualified Control.Exception as E
import Control.Monad (when)
import Control.Monad.Trans (MonadIO (..))
import qualified Data.ByteString as BS
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BC
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy.Encoding (decodeUtf8')
import Text.Printf (printf)
import Data.Char (ord, isAscii, isSpace)
import System.Directory
import System.Environment
import System.Exit (ExitCode (..))
import System.FilePath
import System.IO (stderr, hClose)
import System.IO.Temp (withSystemTempDirectory, withTempDirectory,
withTempFile)
import qualified System.IO.Error as IE
import Text.DocLayout (literal)
import Text.Pandoc.Definition
import Text.Pandoc.Error (PandocError (PandocPDFProgramNotFoundError))
import Text.Pandoc.MIME (getMimeType)
import Text.Pandoc.Options (HTMLMathMethod (..), WriterOptions (..))
import Text.Pandoc.Process (pipeProcess)
import System.Process (readProcessWithExitCode)
import Text.Pandoc.Shared (inDirectory, stringify, tshow)
import qualified Text.Pandoc.UTF8 as UTF8
import Text.Pandoc.Walk (walkM)
import Text.Pandoc.Writers.Shared (getField, metaToContext)
#ifdef _WINDOWS
import Data.List (intercalate)
#endif
import Data.List (isPrefixOf, find)
import Text.Pandoc.Class.PandocIO (PandocIO, extractMedia, runIOorExplode)
import Text.Pandoc.Class.PandocMonad (fillMediaBag, getCommonState, getVerbosity,
putCommonState, report, setVerbosity)
import Text.Pandoc.Logging
#ifdef _WINDOWS
changePathSeparators :: FilePath -> FilePath
changePathSeparators =
-- We filter out backslashes because an initial `C:\` gets
-- retained by `splitDirectories`, see #6173:
intercalate "/" . map (filter (/='\\')) . splitDirectories
#endif
makePDF :: String -- ^ pdf creator (pdflatex, lualatex, xelatex,
-- wkhtmltopdf, weasyprint, prince, context, pdfroff,
-- or path to executable)
-> [String] -- ^ arguments to pass to pdf creator
-> (WriterOptions -> Pandoc -> PandocIO Text) -- ^ writer
-> WriterOptions -- ^ options
-> Pandoc -- ^ document
-> PandocIO (Either ByteString ByteString)
makePDF program pdfargs writer opts doc =
case takeBaseName program of
"wkhtmltopdf" -> makeWithWkhtmltopdf program pdfargs writer opts doc
prog | prog `elem` ["weasyprint", "prince"] -> do
source <- writer opts doc
verbosity <- getVerbosity
liftIO $ html2pdf verbosity program pdfargs source
"pdfroff" -> do
source <- writer opts doc
let args = ["-ms", "-mpdfmark", "-mspdf",
"-e", "-t", "-k", "-KUTF-8", "-i"] ++ pdfargs
verbosity <- getVerbosity
liftIO $ generic2pdf verbosity program args source
baseProg -> do
commonState <- getCommonState
verbosity <- getVerbosity
-- latex has trouble with tildes in paths, which
-- you find in Windows temp dir paths with longer
-- user names (see #777)
let withTempDir templ action = do
tmp <- getTemporaryDirectory
uname <- E.catch
(do (ec, sout, _) <- readProcessWithExitCode "uname" ["-o"] ""
if ec == ExitSuccess
then return $ Just $ filter (not . isSpace) sout
else return Nothing)
(\(_ :: E.SomeException) -> return Nothing)
if '~' `elem` tmp || uname == Just "Cygwin" -- see #5451
then withTempDirectory "." templ action
else withSystemTempDirectory templ action
(newCommonState, res) <- liftIO $ withTempDir "tex2pdf." $ \tmpdir' -> do
#ifdef _WINDOWS
-- note: we want / even on Windows, for TexLive
let tmpdir = changePathSeparators tmpdir'
#else
let tmpdir = tmpdir'
#endif
runIOorExplode $ do
putCommonState commonState
doc' <- handleImages opts tmpdir doc
source <- writer opts doc'
res <- case baseProg of
"context" -> context2pdf verbosity program pdfargs tmpdir source
"tectonic" -> tectonic2pdf verbosity program pdfargs tmpdir source
prog | prog `elem` ["pdflatex", "lualatex", "xelatex", "latexmk"]
-> tex2pdf verbosity program pdfargs tmpdir source
_ -> return $ Left $ UTF8.fromStringLazy
$ "Unknown program " ++ program
cs <- getCommonState
return (cs, res)
putCommonState newCommonState
return res
makeWithWkhtmltopdf :: String -- ^ wkhtmltopdf or path
-> [String] -- ^ arguments
-> (WriterOptions -> Pandoc -> PandocIO Text) -- ^ writer
-> WriterOptions -- ^ options
-> Pandoc -- ^ document
-> PandocIO (Either ByteString ByteString)
makeWithWkhtmltopdf program pdfargs writer opts doc@(Pandoc meta _) = do
let mathArgs = case writerHTMLMathMethod opts of
-- with MathJax, wait til all math is rendered:
MathJax _ -> ["--run-script", "MathJax.Hub.Register.StartupHook('End Typeset', function() { window.status = 'mathjax_loaded' });",
"--window-status", "mathjax_loaded"]
_ -> []
meta' <- metaToContext opts
(return . literal . stringify)
(return . literal . stringify)
meta
let toArgs (f, mbd) = maybe [] (\d -> ["--" <> f, T.unpack d]) mbd
let args = mathArgs ++ concatMap toArgs
[("page-size", getField "papersize" meta')
,("title", getField "title" meta')
,("margin-bottom", Just $ fromMaybe "1.2in"
(getField "margin-bottom" meta'))
,("margin-top", Just $ fromMaybe "1.25in"
(getField "margin-top" meta'))
,("margin-right", Just $ fromMaybe "1.25in"
(getField "margin-right" meta'))
,("margin-left", Just $ fromMaybe "1.25in"
(getField "margin-left" meta'))
,("footer-html", getField "footer-html" meta')
,("header-html", getField "header-html" meta')
] ++ ("--enable-local-file-access" : pdfargs)
-- see #6474
source <- writer opts doc
verbosity <- getVerbosity
liftIO $ html2pdf verbosity program args source
handleImages :: WriterOptions
-> FilePath -- ^ temp dir to store images
-> Pandoc -- ^ document
-> PandocIO Pandoc
handleImages opts tmpdir doc =
fillMediaBag doc >>=
extractMedia tmpdir >>=
walkM (convertImages opts tmpdir)
convertImages :: WriterOptions -> FilePath -> Inline -> PandocIO Inline
convertImages opts tmpdir (Image attr ils (src, tit)) = do
img <- liftIO $ convertImage opts tmpdir $ T.unpack src
newPath <-
case img of
Left e -> do
report $ CouldNotConvertImage src e
return src
Right fp -> return $ T.pack fp
return (Image attr ils (newPath, tit))
convertImages _ _ x = return x
-- Convert formats which do not work well in pdf to png
convertImage :: WriterOptions -> FilePath -> FilePath
-> IO (Either Text FilePath)
convertImage opts tmpdir fname = do
let dpi = show $ writerDpi opts
case mime of
Just "image/png" -> doNothing
Just "image/jpeg" -> doNothing
Just "application/pdf" -> doNothing
-- Note: eps is converted by pdflatex using epstopdf.pl
Just "application/eps" -> doNothing
Just "image/svg+xml" -> E.catch (do
(exit, _) <- pipeProcess Nothing "rsvg-convert"
["-f","pdf","-a","--dpi-x",dpi,"--dpi-y",dpi,
"-o",pdfOut,fname] BL.empty
if exit == ExitSuccess
then return $ Right pdfOut
else return $ Left "conversion from SVG failed")
(\(e :: E.SomeException) -> return $ Left $
"check that rsvg-convert is in path.\n" <>
tshow e)
_ -> JP.readImage fname >>= \case
Left e -> return $ Left $ T.pack e
Right img ->
E.catch (Right pngOut <$ JP.savePngImage pngOut img) $
\(e :: E.SomeException) -> return (Left (tshow e))
where
pngOut = replaceDirectory (replaceExtension fname ".png") tmpdir
pdfOut = replaceDirectory (replaceExtension fname ".pdf") tmpdir
mime = getMimeType fname
doNothing = return (Right fname)
tectonic2pdf :: Verbosity -- ^ Verbosity level
-> String -- ^ tex program
-> [String] -- ^ Arguments to the latex-engine
-> FilePath -- ^ temp directory for output
-> Text -- ^ tex source
-> PandocIO (Either ByteString ByteString)
tectonic2pdf verbosity program args tmpDir source = do
(exit, log', mbPdf) <- runTectonic verbosity program args tmpDir source
case (exit, mbPdf) of
(ExitFailure _, _) -> return $ Left $ extractMsg log'
(ExitSuccess, Nothing) -> return $ Left ""
(ExitSuccess, Just pdf) -> do
missingCharacterWarnings verbosity log'
return $ Right pdf
tex2pdf :: Verbosity -- ^ Verbosity level
-> String -- ^ tex program
-> [String] -- ^ Arguments to the latex-engine
-> FilePath -- ^ temp directory for output
-> Text -- ^ tex source
-> PandocIO (Either ByteString ByteString)
tex2pdf verbosity program args tmpDir source = do
let numruns | takeBaseName program == "latexmk" = 1
| "\\tableofcontents" `T.isInfixOf` source = 3 -- to get page numbers
| otherwise = 2 -- 1 run won't give you PDF bookmarks
(exit, log', mbPdf) <- runTeXProgram verbosity program args numruns
tmpDir source
case (exit, mbPdf) of
(ExitFailure _, _) -> do
let logmsg = extractMsg log'
let extramsg =
case logmsg of
x | "! Package inputenc Error" `BC.isPrefixOf` x
&& program /= "xelatex"
-> "\nTry running pandoc with --pdf-engine=xelatex."
_ -> ""
return $ Left $ logmsg <> extramsg
(ExitSuccess, Nothing) -> return $ Left ""
(ExitSuccess, Just pdf) -> do
missingCharacterWarnings verbosity log'
return $ Right pdf
missingCharacterWarnings :: Verbosity -> ByteString -> PandocIO ()
missingCharacterWarnings verbosity log' = do
let ls = BC.lines log'
let isMissingCharacterWarning = BC.isPrefixOf "Missing character: "
let toCodePoint c
| isAscii c = T.singleton c
| otherwise = T.pack $ c : " (U+" ++ printf "%04X" (ord c) ++ ")"
let addCodePoint = T.concatMap toCodePoint
let warnings = [ addCodePoint (T.pack $ utf8ToString (BC.drop 19 l))
| l <- ls
, isMissingCharacterWarning l
]
setVerbosity verbosity
mapM_ (report . MissingCharacter) warnings
-- parsing output
extractMsg :: ByteString -> ByteString
extractMsg log' = do
let msg' = dropWhile (not . ("!" `BC.isPrefixOf`)) $ BC.lines log'
let (msg'',rest) = break ("l." `BC.isPrefixOf`) msg'
let lineno = take 1 rest
if null msg'
then log'
else BC.unlines (msg'' ++ lineno)
extractConTeXtMsg :: ByteString -> ByteString
extractConTeXtMsg log' = do
let msg' = take 1 $
dropWhile (not . ("tex error" `BC.isPrefixOf`)) $ BC.lines log'
if null msg'
then log'
else BC.unlines msg'
-- running tex programs
runTectonic :: Verbosity -> String -> [String] -> FilePath
-> Text -> PandocIO (ExitCode, ByteString, Maybe ByteString)
runTectonic verbosity program args' tmpDir' source = do
let getOutDir acc (a:b:xs) = if a `elem` ["-o", "--outdir"]
then (reverse acc ++ xs, Just b)
else getOutDir (b:a:acc) xs
getOutDir acc xs = (reverse acc ++ xs, Nothing)
(args, outDir) = getOutDir [] args'
tmpDir = fromMaybe tmpDir' outDir
liftIO $ createDirectoryIfMissing True tmpDir
-- run tectonic on stdin so it reads \include commands from $PWD instead of a temp directory
let sourceBL = BL.fromStrict $ UTF8.fromText source
let programArgs = ["--outdir", tmpDir] ++ args ++ ["-"]
env <- liftIO getEnvironment
when (verbosity >= INFO) $ liftIO $
showVerboseInfo (Just tmpDir) program programArgs env
(utf8ToString sourceBL)
(exit, out) <- liftIO $ E.catch
(pipeProcess (Just env) program programArgs sourceBL)
(handlePDFProgramNotFound program)
when (verbosity >= INFO) $ liftIO $ do
UTF8.hPutStrLn stderr "[makePDF] Running"
BL.hPutStr stderr out
UTF8.hPutStr stderr "\n"
let pdfFile = tmpDir ++ "/texput.pdf"
(_, pdf) <- getResultingPDF Nothing pdfFile
return (exit, out, pdf)
-- read a pdf that has been written to a temporary directory, and optionally read
-- logs
getResultingPDF :: Maybe String -> String -> PandocIO (Maybe ByteString, Maybe ByteString)
getResultingPDF logFile pdfFile = do
pdfExists <- liftIO $ doesFileExist pdfFile
pdf <- if pdfExists
-- We read PDF as a strict bytestring to make sure that the
-- temp directory is removed on Windows.
-- See https://github.com/jgm/pandoc/issues/1192.
then (Just . BL.fromChunks . (:[])) `fmap`
liftIO (BS.readFile pdfFile)
else return Nothing
-- Note that some things like Missing character warnings
-- appear in the log but not on stderr, so we prefer the log:
log' <- case logFile of
Just logFile' -> do
logExists <- liftIO $ doesFileExist logFile'
if logExists
then liftIO $ Just <$> BL.readFile logFile'
else return Nothing
Nothing -> return Nothing
return (log', pdf)
-- Run a TeX program on an input bytestring and return (exit code,
-- contents of stdout, contents of produced PDF if any). Rerun
-- a fixed number of times to resolve references.
runTeXProgram :: Verbosity -> String -> [String] -> Int -> FilePath
-> Text -> PandocIO (ExitCode, ByteString, Maybe ByteString)
runTeXProgram verbosity program args numRuns tmpDir' source = do
let isOutdirArg x = "-outdir=" `isPrefixOf` x ||
"-output-directory=" `isPrefixOf` x
let tmpDir =
case find isOutdirArg args of
Just x -> drop 1 $ dropWhile (/='=') x
Nothing -> tmpDir'
liftIO $ createDirectoryIfMissing True tmpDir
let file = tmpDir ++ "/input.tex" -- note: tmpDir has / path separators
liftIO $ BS.writeFile file $ UTF8.fromText source
let isLatexMk = takeBaseName program == "latexmk"
programArgs | isLatexMk = ["-interaction=batchmode", "-halt-on-error", "-pdf",
"-quiet", "-outdir=" ++ tmpDir] ++ args ++ [file]
| otherwise = ["-halt-on-error", "-interaction", "nonstopmode",
"-output-directory", tmpDir] ++ args ++ [file]
env' <- liftIO getEnvironment
let sep = [searchPathSeparator]
let texinputs = maybe (tmpDir ++ sep) ((tmpDir ++ sep) ++)
$ lookup "TEXINPUTS" env'
let env'' = ("TEXINPUTS", texinputs) :
("TEXMFOUTPUT", tmpDir) :
[(k,v) | (k,v) <- env'
, k /= "TEXINPUTS" && k /= "TEXMFOUTPUT"]
when (verbosity >= INFO) $ liftIO $
UTF8.readFile file >>=
showVerboseInfo (Just tmpDir) program programArgs env''
let runTeX runNumber = do
(exit, out) <- liftIO $ E.catch
(pipeProcess (Just env'') program programArgs BL.empty)
(handlePDFProgramNotFound program)
when (verbosity >= INFO) $ liftIO $ do
UTF8.hPutStrLn stderr $ "[makePDF] Run #" ++ show runNumber
BL.hPutStr stderr out
UTF8.hPutStr stderr "\n"
if runNumber < numRuns
then runTeX (runNumber + 1)
else do
let logFile = replaceExtension file ".log"
let pdfFile = replaceExtension file ".pdf"
(log', pdf) <- getResultingPDF (Just logFile) pdfFile
return (exit, fromMaybe out log', pdf)
runTeX 1
generic2pdf :: Verbosity
-> String
-> [String]
-> Text
-> IO (Either ByteString ByteString)
generic2pdf verbosity program args source = do
env' <- getEnvironment
when (verbosity >= INFO) $
showVerboseInfo Nothing program args env' (T.unpack source)
(exit, out) <- E.catch
(pipeProcess (Just env') program args
(BL.fromStrict $ UTF8.fromText source))
(handlePDFProgramNotFound program)
return $ case exit of
ExitFailure _ -> Left out
ExitSuccess -> Right out
html2pdf :: Verbosity -- ^ Verbosity level
-> String -- ^ Program (wkhtmltopdf, weasyprint, prince, or path)
-> [String] -- ^ Args to program
-> Text -- ^ HTML5 source
-> IO (Either ByteString ByteString)
html2pdf verbosity program args source =
-- write HTML to temp file so we don't have to rewrite
-- all links in `a`, `img`, `style`, `script`, etc. tags,
-- and piping to weasyprint didn't work on Windows either.
withTempFile "." "html2pdf.html" $ \file h1 ->
withTempFile "." "html2pdf.pdf" $ \pdfFile h2 -> do
hClose h1
hClose h2
BS.writeFile file $ UTF8.fromText source
let pdfFileArgName = ["-o" | takeBaseName program == "prince"]
let programArgs = args ++ [file] ++ pdfFileArgName ++ [pdfFile]
env' <- getEnvironment
when (verbosity >= INFO) $
UTF8.readFile file >>=
showVerboseInfo Nothing program programArgs env'
(exit, out) <- E.catch
(pipeProcess (Just env') program programArgs BL.empty)
(handlePDFProgramNotFound program)
when (verbosity >= INFO) $ do
BL.hPutStr stderr out
UTF8.hPutStr stderr "\n"
pdfExists <- doesFileExist pdfFile
mbPdf <- if pdfExists
-- We read PDF as a strict bytestring to make sure that the
-- temp directory is removed on Windows.
-- See https://github.com/jgm/pandoc/issues/1192.
then Just . BL.fromChunks . (:[]) <$> BS.readFile pdfFile
else return Nothing
return $ case (exit, mbPdf) of
(ExitFailure _, _) -> Left out
(ExitSuccess, Nothing) -> Left ""
(ExitSuccess, Just pdf) -> Right pdf
context2pdf :: Verbosity -- ^ Verbosity level
-> String -- ^ "context" or path to it
-> [String] -- ^ extra arguments
-> FilePath -- ^ temp directory for output
-> Text -- ^ ConTeXt source
-> PandocIO (Either ByteString ByteString)
context2pdf verbosity program pdfargs tmpDir source =
liftIO $ inDirectory tmpDir $ do
let file = "input.tex"
BS.writeFile file $ UTF8.fromText source
let programArgs = "--batchmode" : pdfargs ++ [file]
env' <- getEnvironment
when (verbosity >= INFO) $
UTF8.readFile file >>=
showVerboseInfo (Just tmpDir) program programArgs env'
(exit, out) <- E.catch
(pipeProcess (Just env') program programArgs BL.empty)
(handlePDFProgramNotFound program)
when (verbosity >= INFO) $ do
BL.hPutStr stderr out
UTF8.hPutStr stderr "\n"
let pdfFile = replaceExtension file ".pdf"
pdfExists <- doesFileExist pdfFile
mbPdf <- if pdfExists
-- We read PDF as a strict bytestring to make sure that the
-- temp directory is removed on Windows.
-- See https://github.com/jgm/pandoc/issues/1192.
then (Just . BL.fromChunks . (:[])) `fmap` BS.readFile pdfFile
else return Nothing
case (exit, mbPdf) of
(ExitFailure _, _) -> do
let logmsg = extractConTeXtMsg out
return $ Left logmsg
(ExitSuccess, Nothing) -> return $ Left ""
(ExitSuccess, Just pdf) -> return $ Right pdf
showVerboseInfo :: Maybe FilePath
-> String
-> [String]
-> [(String, String)]
-> String
-> IO ()
showVerboseInfo mbTmpDir program programArgs env source = do
case mbTmpDir of
Just tmpDir -> do
UTF8.hPutStrLn stderr "[makePDF] temp dir:"
UTF8.hPutStrLn stderr tmpDir
Nothing -> return ()
UTF8.hPutStrLn stderr "[makePDF] Command line:"
UTF8.hPutStrLn stderr $ program ++ " " ++ unwords (map show programArgs)
UTF8.hPutStr stderr "\n"
UTF8.hPutStrLn stderr "[makePDF] Environment:"
mapM_ (UTF8.hPutStrLn stderr . show) env
UTF8.hPutStr stderr "\n"
UTF8.hPutStrLn stderr "[makePDF] Source:"
UTF8.hPutStrLn stderr source
handlePDFProgramNotFound :: String -> IE.IOError -> IO a
handlePDFProgramNotFound program e
| IE.isDoesNotExistError e =
E.throwIO $ PandocPDFProgramNotFoundError $ T.pack program
| otherwise = E.throwIO e
utf8ToString :: ByteString -> String
utf8ToString lbs =
case decodeUtf8' lbs of
Left _ -> BC.unpack lbs -- if decoding fails, treat as latin1
Right t -> TL.unpack t
|