Search code examples
bytepdf-generationclojurescript

How to create a vector of bytes from pdf file with ClojureScript?


I want to convert a pdf file to a vector of bytes like: [1 23 4 43 .....], using ClojureScript. Please, any ideas?

Thanks a lot!


Solution

  • I wrote this quick example that should get you most of what you need for a web version with the HTML5 Files API:

    (defn handle-files [fs]
      (let [file  (aget (.-files fs) 0) ;; the first file
            slice (.slice file 0 100)]  ;; a slice with the first 100 bytes
    
        ;; The API to get the file contents returns a promise, so we'll update
        ;; the atom when the data is available
        (-> slice .text (.then #(swap! file-info assoc-in [:contents] %)))
    
        ;; Most of the file info is available right away
        (reset! file-info {:name (.-name file)
                           :size (.-size file)
                           :type (.-type file)})))
    
    ;; App initialization
    
    (defn mount-root []
      (rdom/render [example-app] (.getElementById js/document "app"))
    
      ;; register fn to check on the file[s] we want the browser to scan
      (-> (.getElementById js/document "input")
          (.addEventListener "change" #(handle-files (.-target %)) false)))
    

    You can find a working example on this repo: https://github.com/dfuenzalida/cljs-files-api