Generate Custom PDF Using Print Module In Drupal Skip to main content

PDF Using Print Module In Drupal

Saurabh Dhariwal

Saurabh Dhariwal

Custom pdf

Please follow the below steps to Generate custom pdf:

1: First you need to install and enable print module.
2: Download dompdf from github dompdf on github.
3: Put dompdf library in "/sites/all/modules/print/lib/dompdf".
4: Add below code at the starting of the custom module file.

    use Dompdf\Dompdf;

5: Create your html structure that you want to print in pdf and set your html structure to $result like below example.


    $result = '<table>
      <tr>
        <td>
          fitst row first column
        </td>
        <td>
          fitst row second column
        </td>
      </tr>
    </table>';
  

6: Add condition for print module and not empty result. 

  if (module_exists('print') && !empty($result))

7: If condition is TRUE then under condition add library path like that 

$file_path_include = drupal_get_path('module', 'print') .'/lib/dompdf/autoload.inc.php';
    require_once $file_path_include;

8: Create object for Dompdf.

    $dompdf = new Dompdf();

9: Add your html structure in object's load_html method.

    $dompdf->load_html($result);

10: Add below line to generate output.

 $dompdf->render();
    $pdfoutput = $dompdf->output();

11: Set file name and file path that you want to store. Keep the name dynamic if there are multiple pdfs by appending date-time.

$filename = 'demo.pdf';
    $filepath = 'sites/default/files/pdf/demo.pdf';

12: Write file using below code. This will generate pdf at "sites/default/files/pdf/demo.pdf".

    $fp = fopen($filepath, "w+");
    fwrite($fp, $pdfoutput);
    fclose($fp);

Here is the full code:

    use Dompdf\Dompdf;

    $result = '<table>
      <tr>
        <td>
          fitst row first column
        </td>
        <td>
          fitst row second column
        </td>
      </tr>
    </table>';

    if (module_exists('print') && !empty($result)) {
      $dompdf = new Dompdf();
      $dompdf->load_html($result);
      $dompdf->render();
      $pdfoutput = $dompdf->output();
      $filename = 'demo.pdf';
      $filepath = 'sites/default/files/pdf/demo.pdf';
      $fp = fopen($filepath, "w+");
      fwrite($fp, $pdfoutput);
      fclose($fp);
    }

Hope this demo helps you.Need more assistance regarding Drupal Web Design Services...!