First of all, sorry for my english: i'm not british/american.

Here is my problem. I've got a folder named pdf with lots of files pdf inside it. I've got another folder named thumbnail, which is empty. I want to create jpg images preview of each pdf to use them in my HTML webpages as previews of the pdf.

To do this I'm using a software called IMAGEMAGICK. I tried to put the code inside my PHP files to get the purpose, but it doesn't work. As you understood, I have created a small search engine with apache, mysql to search for pdf locally (offline). Now I want to add a "preview" of the first page of pdfs. Instead, it works by bash command line and the code is:

convert pdf/name_of_the_file_pdf.pdf[0] name_of_the_imagefile.jpg

(The zero stands for that the image is taken from the FIRST page of pdf) How can i make a script that takes each name of pdf files and put it into that code???? To list all the file, I did

ls >pdf

but with the little knowledge I have I can't go further.... Some pdf's names contain spaces....Is that a problem?

PDF files are so many that i can't do the task typing every name,it wouldn't be a nice and clever work!!!! Thanks a lot in advance!!!


Any solution that uses the ls command will eventually fail, but don't fret; bash can handle any and all filenames safely without involving an external command (like ls) to "list" them.

To make a filename.jpg from every filename.pdf in the current directory, you can do:

for file in ./*.pdf; do
    convert "$file[0]" "${file%.pdf}.jpg"

You can also do that in one line

for file in ./*.pdf; do convert "$file[0]" "${file%.pdf}.jpg"; done

The double quotes (") are very important to avoid wordsplitting and pathname expansion from the result of the parameter expansions.

$file and ${file%.pdf} are called parameter expansions. See http://mywiki.wooledge.org/BashFAQ/073 and http://mywiki.wooledge.org/BashFAQ/100 for more on parameter expansions and string manipulation in bash in general.

EDIT: And reading the question again, I see you wanted the jpegs in the parent directory of the pdfs, so I'll include the necessary modifications for that as well:

for file in pdf/*.pdf; do
    convert "$file[0]" "./${basename%.pdf}.jpg"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.