7

I use Haskell-Chart according to the example eample-1. Haskell-Chart generates content to file

toFile def "example1_big.png" $ do
...

Is it possible generate content of chart to ByteString instead file? I can not find a solution in the documentation.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
QSpider
  • 537
  • 2
  • 10

2 Answers2

8

Unfortunately this is not possible is a direct manner. toFile calls upon functions in the cairo library like withPDFSurface, withSVGSurface which themselves call into the cairo C-library and only take file names.

You can always write to a temporary file and read the contents back in like this:

import System.IO.Temp  -- from the temporary package
import qualified Data.ByteString.Char8 as BS

...
bs <- withSystemTempFile "chart-XXXXXXX" $ \path _ -> do
        toFile def path $ do ...
        BS.readFile path
ErikR
  • 51,541
  • 9
  • 73
  • 124
  • I think `readFile` is wrong here because Haskell is lazy. You should instead read from the open handle with something like `hGetContents`: https://stackoverflow.com/questions/61177386/unable-to-read-from-temporary-file – nevrome Sep 06 '22 at 13:03
2

it's possible but only with Diagrams backend which is slower.

`

import Graphics.Rendering.Chart.State(EC, execEC)
import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Diagrams
import qualified Diagrams.Backend.SVG as DSVG
import qualified Diagrams.Prelude as D
import qualified Diagrams.TwoD as D2

toSVG :: (Default r,ToRenderable r) => EC r () -> IO String
toSVG ec = do
    fontSelector <- _fo_fonts def
    let cb = render (toRenderable (execEC ec))(_fo_size def)
    let (w, h) = (800 :: Double, 600 :: Double)
    let env = createEnv vectorAlignmentFns w h fontSelector
    let (d, a) = runBackend env cb
        opts = DSVG.SVGOptions (D2.dims2D w h) Nothing T.empty [] True
        svg = D.renderDia DSVG.SVG opts d
    return $ show svg

`

shem
  • 83
  • 5