public function combine_files($contextid, $itemid) {
        global $CFG;

        $currentstatus = $this->get_status();
        $readystatuslist = [self::STATUS_READY, self::STATUS_READY_PARTIAL];
        if ($currentstatus === self::STATUS_FAILED) {
            $this->store_empty_document($contextid, $itemid);

            return $this;
        } else if (!in_array($currentstatus, $readystatuslist)) {
            // The document is either:
            // * already combined; or
            // * pending input being fully converted; or
            // * unable to continue due to an issue with the input documents.
            //
            // Exit early as we cannot continue.
            return $this;
        }

        require_once($CFG->libdir . '/pdflib.php');

        $pdf = new pdf();
        $files = $this->get_source_files();
        $compatiblepdfs = [];

        foreach ($files as $file) {
            // Check that each file is compatible and add it to the list.
            // Note: We drop non-compatible files.
            $compatiblepdf = false;
            if (is_a($file, \core_files\conversion::class)) {
                $status = $file->get('status');
                if ($status == \core_files\conversion::STATUS_COMPLETE) {
                    $compatiblepdf = pdf::ensure_pdf_compatible($file->get_destfile());
                }
            } else {
                $compatiblepdf = pdf::ensure_pdf_compatible($file);
            }

            if ($compatiblepdf) {
                $compatiblepdfs[] = $compatiblepdf;
            }
        }

        $tmpdir = make_request_directory();
        $tmpfile = $tmpdir . '/' . document_services::COMBINED_PDF_FILENAME;

        try {
            $pagecount = $pdf->combine_pdfs($compatiblepdfs, $tmpfile);
            $pdf->Close();
        } catch (\Exception $e) {
            // Unable to combine the PDF.
            debugging('TCPDF could not process the pdf files:' . $e->getMessage(), DEBUG_DEVELOPER);

            $pdf->Close();
            return $this->mark_combination_failed();
        }

        // Verify the PDF.
        $verifypdf = new pdf();
        $verifypagecount = $verifypdf->load_pdf($tmpfile);
        $verifypdf->Close();

        if ($verifypagecount <= 0) {
            // No pages were found in the combined PDF.
            return $this->mark_combination_failed();
        }

        // Store the newly created file as a stored_file.
        $this->store_combined_file($tmpfile, $contextid, $itemid, ($currentstatus == self::STATUS_READY_PARTIAL));

        // Note the verified page count.
        $this->pagecount = $verifypagecount;

        return $this;
    }