Search code examples
shellshgraphicsmagick

How to run/call a shell script function with graphicsmagick


I have a pdf of LaTeX math tasks which I would like to convert to png using graphicsmagick. I tried a lot of online converter and similar tools, none was working for me. I have separate tasks on single pages in my pdf document. A colleague suggested to use graphicsmagick. He also provided a code snippet, which I can understand in principle. Everything comes in a shell script, which I never used so far.

My question is: How do I use/execute/call the given code snippet?

This is what I got (I saved it in my working directory as exam.sh):

function ex {
p=$1
gm convert -trim -density 300x300 file.pdf[$p] /tmp/page.png
H=$(gm identify /tmp/page.png -format "%h")
gm convert page.png -background white -extent 2000x$H auf.png
}

Here is what I managed/tried to do:

  • Install Ubuntu on Windows 10
  • Use the terminal to navigate to my directory (which include a .sh of the code snippet and my file.pdf)
  • I can call a script: I created a hello.sh which echos "hello world" (I call it by ´source hello.sh´)
  • I can call a script which includes a function with parameters: I created a add.sh (from youtube-video), though I havn't managed to call a function from "outside of the script", i.e. save/activate the function within terminal.
  • I installed graphicsmagick and called a one-line, I can do "gm convert -trim -density 300x300 file.pdf[$p] /tmp/page.png" manually.
  • I further noticed, there are some issues with editing shell scripts in Windows texteditor, therefore I used "nano" in terminal.

When I try

source exam.sh

It returns "syntax error near unexpected token "

It seems that page is the only parameter I have to give to the function.

ex 1 

This doesn't work either.

I appreciate any advice about what I have to include in the script (perhaps specifiy some kind of shell?), what I have to write in the terminal (chmod + x?) in order to tell the terminal my function exists and how to execute the function or give parameters to the function in order to finally get some png.

Update

Here is a picture for illustration. I need to crop whatever text/formula is given on a otherwise blank A4-page. The final crop should be 2000 pixel wide. With relative height, dependent on how "long" text/formula/picture is.

enter image description here


Solution

  • You should be able to do it all in one like this, without Ubuntu or shell scripts, just in Command Prompt:

    gm convert -density 300x300 file.pdf[0] -trim -background white -extent 2000x auf.png
    

    You can probably make a batch file called EXTRACT.BAT like this:

    gm convert -density 300x300 %1[%2] -trim -background white -extent 2000x auf.png
    

    Then you should be able to do:

    EXTRACT FILE.PDF 2
    

    to extract page 3 (because first page is page zero) of FILE.PDF