@@ -36,42 +36,37 @@ import Text.Pandoc.Readers.TeXMath
3636import Text.Pandoc.Templates (renderTemplate')
3737import Text.Pandoc.Walk
3838import Data.List ( isSuffixOf, intercalate )
39−import Data.Char ( ord, chr, isDigit, toLower )
40−import System.FilePath ( takeExtension )
39+import Data.Char ( ord, chr, isDigit )
4140import qualified Data.ByteString as B
4241import qualified Data.Map as M
4342import Text.Printf ( printf )
44−import Network.URI ( isURI, unEscapeString )
45−import qualified Control.Exception as E
4643
47−-- | Convert Image inlines into a raw RTF embedded image, read from a file.
44+-- | Convert Image inlines into a raw RTF embedded image, read from a file,
45+-- or a MediaBag, or the internet.
4846-- If file not found or filetype not jpeg or png, leave the inline unchanged.
49−rtfEmbedImage :: Inline -> IO Inline
50−rtfEmbedImage x@(Image _ (src,_)) = do
51− let ext = map toLower (takeExtension src)
52− if ext `elem` [".jpg",".jpeg",".png"] && not (isURI src)
53− then do
54− let src' = unEscapeString src
55− imgdata <- E.catch (B.readFile src')
56− (\e -> let _ = (e :: E.SomeException) in return B.empty)
57− let bytes = map (printf "%02x") $ B.unpack imgdata
58− let filetype = case ext of
59− ".jpg" -> "\\jpegblip"
60− ".jpeg" -> "\\jpegblip"
61− ".png" -> "\\pngblip"
62− _ -> error "Unknown file type"
63− let raw = "{\\pict" ++ filetype ++ " " ++ concat bytes ++ "}"
64− return $ if B.null imgdata
65− then x
66− else RawInline (Format "rtf") raw
67− else return x
68−rtfEmbedImage x = return x
47+rtfEmbedImage :: WriterOptions -> Inline -> IO Inline
48+rtfEmbedImage opts x@(Image _ (src,_)) = do
49+ result <- fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
50+ case result of
51+ Right (imgdata, Just mime)
52+ | mime == "image/jpeg" || mime == "image/png" -> do
53+ let bytes = map (printf "%02x") $ B.unpack imgdata
54+ let filetype = case mime of
55+ "image/jpeg" -> "\\jpegblip"
56+ "image/png" -> "\\pngblip"
57+ _ -> error "Unknown file type"
58+ let raw = "{\\pict" ++ filetype ++ " " ++ concat bytes ++ "}"
59+ return $ if B.null imgdata
60+ then x
61+ else RawInline (Format "rtf") raw
62+ _ -> return x
63+rtfEmbedImage _ x = return x
6964
7065-- | Convert Pandoc to a string in rich text format, with
7166-- images embedded as encoded binary data.
7267writeRTFWithEmbeddedImages :: WriterOptions -> Pandoc -> IO String
7368writeRTFWithEmbeddedImages options doc =
74− writeRTF options `fmap` walkM rtfEmbedImage doc
69+ writeRTF options `fmap` walkM (rtfEmbedImage options) doc
7570
7671-- | Convert Pandoc to a string in rich text format.
7772writeRTF :: WriterOptions -> Pandoc -> String