Reputation: 89
I am using the following php function to split a pdf file into two files according to page number. The source file has 14 pages. I am creating the two files: First 12 pages for one and the last two pages for the second fils. But I am getting a different site format for the both created files than the source file. How can I improve the function to make sure that I am getting the exact site format as the source file? I am using the pdf-reader library. Or what could you recomment to use as tool to reach this?
function split_pdf14($filename, $end_directory = false, $numberOfPages = 12, $row) {
$pdf = new \TCPDI();
$pagecount = $pdf->setSourceFile($filename);
$pagesDone = 0;
if ($pagecount > $numberOfPages) {
$maxFiles = floor($pagecount / $numberOfPages);
for ($j = 1; $j <= 2; $j++) {
$new_pdf = new \TCPDI();
$new_pdf->setSourceFile($filename);
for ($i = 1; $i <= $numberOfPages; $i++) {
$pagesDone++;
if ($pagesDone > $pagecount) {
/*
* do nohting
*/
} else {
$new_pdf->AddPage();
$new_pdf->useTemplate($new_pdf->importPage($pagesDone));
}
}
try {
if ($j == 1) {
$new_filename = 'localfiles/' . $row['f_auftragsnr'] . '_' . $row['t_sorte'] . '_' . $row['t_sprache'] . '_' . $row['t_umfang'] . '.pdf';
} else {
$new_filename = 'localfiles/' . $row['f_auftragsnr'] . '_' . $row['t_sorte'] . '_' . $row['t_sprache'] . '_' . $row['t_umfang'] . '_BON.pdf';
}
//$new_pdf->Output($new_filename, "F");
$new_pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/' . $new_filename, 'F');
//$new_pdf->Output('/home/box/public_html/box2019/' . $new_filename, 'F');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$numberOfPages = $pagecount;
}
}
}
Upvotes: 0
Views: 201
Reputation: 5058
You are using the default page format (A4) and orientation.
Your code doesn't care about the size of the imported pages and simply adds A4 portrait pages:
$new_pdf->AddPage();
$new_pdf->useTemplate($new_pdf->importPage($pagesDone));
You simply have to add the pages in the correct size and orientation:
$tplId = $new_pdf->importPage($pagesDone);
$size = $this->getTemplatesize($tplId);
$new_pdf->AddPage($size['w'] > $size['h'] ? 'L' : 'P', [$s['w'], $s['h']]);
$new_pdf->useTemplate($tplId);
PS: The script you are using (TCPDI) seems to be several years old. You may use the latest official version of FPDI for such task.
Upvotes: 1