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

| By Webner

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>";"




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



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







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');
  	$homepage = $newtext;
  	$pdf = new TCPDF('L');     // ‘L’ for Landscape mode, P for Portrait mode
  	$pdf->SetFont("freeserif", '', 11); // Font settings
  	$pdf->writeHTML($homepage, true, false, true, false, ''); 
  	$pdf->Output($loc, "F");


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');
              echo "Mailed successfully to User";

//same email screenshot


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.

Leave a Reply

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