Completed writePdfImage function