Moodle | Writing HTML content into pdf file and sending the pdf file as attachment

Author - Harleen Kaur
22.06.2017
|
0 Comments
|

To create a new customized plugin with email functionality and sending a pdf file as attachment requires some simple lines of code with TCPDF library file inside the library directory of moodle. And for performing file operations, filelib.php reference is required. For creating pdf file from HTML content, append entire HTML content in a php variable as shown below:-

$newtext = "<div id=\"course_container\">";

$newtext.= "<table class=\"course_grades\" id=\"course_grades\"><thead><tr>";"

--------

     ------------

$newtext.="</table></div>"; 

We can also add css style script to add colors in our pdf file

$newstyle='<style>                 

.redclass_grade{

     color: rgb(255,0,0) !important;

               }

table#all_course_grades{

Border-style:solid;

------------  

    </style>';

$newtext.=$newstyle;

This is the code to display HTML in a PDF:

global $CFG;
  	require_once($CFG->libdir . '/filelib.php');
  	require_once ($CFG->libdir . '/tcpdf/tcpdf.php');
$filename='mypdffile.pdf';
        $loc=$CFG->dataroot.'/'.$filename;
  	$homepage = $newtext;
  	$pdf = new TCPDF('L');     // ‘L’ for Landscape mode, P for Portrait mode
	$pdf->AddPage();
  	$pdf->SetFont("freeserif", '', 11); // Font settings
  	$pdf->writeHTML($homepage, true, false, true, false, ''); 
  	$pdf->Output($loc, "F");

1

To send the pdf file as attachment in email, one important point to remember is that pdf should be stored directly inside the moodledata folder to which $CFG->dataroot points.

Code for sending email as attachment to students enrolled to course:-

$context = context_course::instance ( $courseid );
    $students = get_role_users ( 5, $context );
	
    foreach ($students as $user){
         $success=email_to_user($user, $USER,$subject,$body,$htmlbody, $tmpfile, 'tempfile.pdf');
         if($success){
              echo "Mailed successfully to User";
         }
     }

//same email screenshot

2

The other important point to pay attention to is SMTP settings in moodle to make email functionality work. To specify email settings, Follow the below path to navigate to email settings:

Site Administration-> Plugins ->Message Outputs

Specify the Host, security, username and password fields to complete the SMTP settings.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *