Some of this would depend on your process (e.g. how you put your HTML together). One way I've done it in the past is to save the HTML to a file and render the file to PDF. At the end of the process you can combine the various files as you've indicated. So something like:
$filenames = array();
foreach ( $doc_ids as $doc_id ) {
$html = create_html( $doc_id );
$filename_html = 'someplace/safe/doc' . $doc_id . '.html';
$filename_pdf = 'someplace/safe/doc' . $doc_id . '.pdf';
file_put_contents( $filename_html , $html );
exec( 'dompdf/dompdf.php ' . $filename_html );
if ( file_exists( $filename_pdf ) ) {
$filenames[] = $filename_pdf;
}
}
exec('gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE="merged_pdf.pdf" -dBATCH ' . implode( ' ' , $filenames ) );
Since dompdf is running outside the current process it's memory will be freed up after each render. You do have a bit more resources allocated to overhead, but it's negligible compared to the savings you get.
You can do the same thing in different ways as well. For example, use a cmd script that accepts a parameter indicating the document ID from the database which then puts together the HTML and render in the same file. You'd still get savings in resource usage and the process would be self-contained. Some methods have trade-offs over others (for example, establishing db connections is costly).