summaryrefslogtreecommitdiff
path: root/.config/nushell/web-images-doc.nu
blob: a474003a69bc62cfc2a1f80bce9af839bf18109c (plain)
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
# Download images from a website and merge them to a (PDF) document
export def main [
  url: string, # URL of the website
  --output_filename: string = 'out.pdf', # Output filename, the file type must be compatible with `magick`
  --query: string = 'img' # Selector query, e.g. to target a class test-img use '.test-img'
] {
  let temp_dir = $"temp_($output_filename | split row "." | get 0)"
  mkdir $temp_dir
  print $"Created temporary directory ($temp_dir)"

  try {
    try {
      http get $url | query web --query $query -m --attribute 'src' | flatten | enumerate | each {|imgsrc| 
        let index = $imgsrc.index + 1
        let filename = $"($temp_dir)/($index | fill -a 'right' -c '0' -w 5).png"
        print $"Downloading image ($index)..."
        http get $imgsrc.item | save $filename
        print $"Image saved to ($filename)"
        sleep 1sec
      }
    } catch { |err|
      print $"\nFailed to download images"
      print $"Error: ($err.msg)"
    }

    let downloaded_images = (ls $temp_dir | get name | sort)
    try {
        magick ...$downloaded_images -border 100x100 $output_filename
        print $"Success! Created ($output_filename) with ($downloaded_images | length) pages."
    } catch { |err|
        print "\nFailed to create PDF. Make sure ImageMagick is installed."
        print $"Error: ($err.msg)"
        return
    }
  } finally {
      rm -rf $temp_dir
  }
}