2

How can I convert a pdf file pages to txt file seperately.

My example code;

pdftotext test.pdf x.txt

My php example code;

 for($i=1; $i<4; $i++){
    if(shell_exec("pdftotext -f $i test.pdf test/t$i.txt")){
        echo 'selam';
    }
 }

But this don't work!

2

The pdftotext program will insert a form feed character (\f) after each PDF page. You can use this to split your text file into multiple files, one per page. First run the command you normally run:

pdftotext test.pdf x.txt

Then, split:

awk -vk=1 '/\f/{k++}{print >> k".txt"}' x.txt 

The awk command will first set the variable k to 1 (-vk=1) and then increment the variable by 1 each time a form feed character is found on a line (/\f/{k++}). Then, it will print each line to a file whose name is the current value of k, plus the string .txt (print >> k".txt"). So, running the script above on a text file containing a converted 5-page PDF file will result in 1.txt, 2.txt, 3.txt, 4.txt and 5.txt.

Note that the script will append to each text file, so running it twice will just add to existing files (if any). To avoid that, remove the files before attempting to run again.

To integrate it into your php code, use:

for($i=1; $i<4; $i++){
    if(shell_exec("pdftotext -f $i test.pdf test/t$i.txt")){
        echo 'selam';
    }
    if(shell_exec("awk -vk=1 -vi="$i" '/\f/{k++}{print >> i"."k".txt"}' t$i.txt")){
        echo 'selam';
    }

}

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.