Forum OpenACS Development: Re: exec bash command pdftk within TCL page

Collapse
Posted by Brian Fenton on
Iuri

I did almost exactly the same thing a while back using ImageMagick. Here's my code if it's any use to you.

ad_proc -public pdf::concat_files {
    {-input_file_list:required}
    {-output_file:required}
}  {

   Makes an operating system call to ImageMagick to concatenate a list of PDF documents.
   ImageMagick is a good choice here as it runs on both Windows and Unix.
   For a Unix-only implementation, I would have used PDFJam/PDFjoin or PDFsam.
    

    @author Brian Fenton Oct 2009

    @param input_file_list - a list of input files (full path names)
    @param output_file -  full path name of the output file 

    @return 1 if all ok, 0 if we have a problem

} {

  #Initialise 
  set return_val 1  

  #if only 1 input file passed in then skip the concatenation
  if { [llength $input_file_list] > 1 } {

    #get location of ImageMagick executable
    set convert_path [parameter::get_from_package_key -package_key acs-workflow -parameter imagemagick_convert_path]

    if {$convert_path ne ""} {
      #set exec_call " $convert_path "
      set exec_call [list $convert_path ]
      foreach infile $input_file_list {
        #check input file is good - exists, permissions etc
        if {![file exists $infile]} {
          set return_val 0
          ns_log Error "pdf::concat_files had an error reading file: $infile not found"
          break
        }

        if {![file readable $infile]} {
          set return_val 0
          ns_log Error "pdf::concat_files had an error reading file: $infile permission denied"
          break
        }

        lappend exec_call "$infile"
      } ;# end foreach

      if {$return_val} {
        #make the call and catch any errors     
        #the ImageMagick generated PDFs are huge, so let's try some compression
        set caught [catch {eval exec -keepnewline $exec_call "-compress Zip" {$output_file}} result]
        if { $caught } {
          set return_val 0
          ns_log Error "pdf::concat_files had an error calling $exec_call. The error was $result"
        } else {
          #check did the concatenated file get created
          if {![file exists $output_file]} {
            set return_val 0
            ns_log Error "pdf::concat_files failed to create $output_file"
          }
        }
      }
    } else {
      set return_val 0
      ns_log Error "pdf::concat_files had an error: ImageMagick not found at $convert_path."
    }
  } else {
    #only 1 input file was passed in, so just do a file copy 
    file copy -force [lindex $input_file_list 0] $output_file
  }
                         
  return $return_val
  
}