Skip to content

Beautiful Open-Source Form Builder

feat: renormalize source_page indices in PDF template updates (#1216)

Chirag Chhatrala585f98dd5ff0
diff --git a/api/app/Http/Controllers/Pdf/PdfTemplateController.php b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
index d16c3ae2f..bb89ee7a6 100644
--- a/api/app/Http/Controllers/Pdf/PdfTemplateController.php
+++ b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
@@ -139,6 +139,20 @@ class PdfTemplateController extends Controller
'errors' => ['file' => [$e->getMessage()]],
], 422);
}
+
+ // Renormalize source_page to match the physical position in the
+ // rebuilt file. The rebuild writes one physical page per manifest
+ // entry (source and blank alike), so the correct value is the
+ // 1-based index of the entry in the manifest.
+ foreach ($pageManifest as $index => &$entry) {
+ if (($entry['type'] ?? 'source') === 'source') {
+ $entry['source_page'] = $index + 1;
+ } else {
+ $entry['source_page'] = null;
+ }
+ }
+ unset($entry);
+ $validated['page_manifest'] = $pageManifest;
$validated['page_count'] = count($pageManifest);
}
$pdfTemplate->update($validated);
diff --git a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
index 19042a8a3..791ae33a6 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
@@ -704,6 +704,312 @@ describe('PDF From-Scratch Default Filename Pattern', function () {
});
});
+describe('PDF Template Update - source_page renormalization', function () {
+ it('renormalizes source_page after removing pages from manifest', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $pdfContent = createMultiPagePdf(6);
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Master Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'master.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 6,
+ 'page_manifest' => PdfTemplate::buildDefaultPageManifest(6),
+ 'zone_mappings' => [],
+ ]);
+
+ // Keep only original pages 1 and 6 (remove 2-5)
+ $response = $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => [
+ ['id' => 'p1', 'type' => 'source', 'source_page' => 1],
+ ['id' => 'p6', 'type' => 'source', 'source_page' => 6],
+ ],
+ 'zone_mappings' => [],
+ ]
+ );
+
+ $response->assertSuccessful();
+ $template->refresh();
+
+ expect($template->page_count)->toBe(2);
+ expect($template->page_manifest)->toHaveCount(2);
+ expect($template->page_manifest[0]['source_page'])->toBe(1);
+ expect($template->page_manifest[1]['source_page'])->toBe(2);
+ });
+
+ it('renormalizes source_page with mixed source and blank pages', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $pdfContent = createMultiPagePdf(4);
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Mixed Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'mixed.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 4,
+ 'page_manifest' => PdfTemplate::buildDefaultPageManifest(4),
+ 'zone_mappings' => [],
+ ]);
+
+ $response = $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => [
+ ['id' => 'p1', 'type' => 'source', 'source_page' => 1],
+ ['id' => 'pb', 'type' => 'blank', 'source_page' => null],
+ ['id' => 'p4', 'type' => 'source', 'source_page' => 4],
+ ],
+ 'zone_mappings' => [],
+ ]
+ );
+
+ $response->assertSuccessful();
+ $template->refresh();
+
+ expect($template->page_count)->toBe(3);
+ expect($template->page_manifest[0]['source_page'])->toBe(1);
+ expect($template->page_manifest[1]['source_page'])->toBeNull();
+ expect($template->page_manifest[2]['source_page'])->toBe(3);
+ });
+
+ it('allows a second save after page removal without error', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $pdfContent = createMultiPagePdf(6);
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Resave Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'resave.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 6,
+ 'page_manifest' => PdfTemplate::buildDefaultPageManifest(6),
+ 'zone_mappings' => [],
+ ]);
+
+ // First save: keep pages 1 and 6
+ $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => [
+ ['id' => 'p1', 'type' => 'source', 'source_page' => 1],
+ ['id' => 'p6', 'type' => 'source', 'source_page' => 6],
+ ],
+ 'zone_mappings' => [],
+ ]
+ )->assertSuccessful();
+
+ $template->refresh();
+
+ // Second save: use the renormalized manifest (source_page 1,2)
+ $response = $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => $template->page_manifest,
+ 'zone_mappings' => [],
+ ]
+ );
+
+ $response->assertSuccessful();
+ $template->refresh();
+
+ expect($template->page_count)->toBe(2);
+ expect($template->page_manifest[0]['source_page'])->toBe(1);
+ expect($template->page_manifest[1]['source_page'])->toBe(2);
+ });
+
+ it('preserves correct page content after blank with distinct page sizes', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace, [
+ 'properties' => [
+ ['id' => 'name', 'name' => 'Name', 'type' => 'text'],
+ ],
+ ]);
+
+ // Pages with different dimensions so we can distinguish them
+ $pdfContent = createMultiPagePdfWithSizes([
+ ['w' => 120, 'h' => 160],
+ ['w' => 140, 'h' => 200],
+ ['w' => 180, 'h' => 250],
+ ['w' => 200, 'h' => 280],
+ ]);
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Sized Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'sized.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 4,
+ 'page_manifest' => PdfTemplate::buildDefaultPageManifest(4),
+ 'zone_mappings' => [],
+ ]);
+
+ // Keep page 1 (120mm), insert blank, keep page 4 (200mm)
+ $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => [
+ ['id' => 'p1', 'type' => 'source', 'source_page' => 1],
+ ['id' => 'pb', 'type' => 'blank', 'source_page' => null],
+ ['id' => 'p4', 'type' => 'source', 'source_page' => 4],
+ ],
+ 'zone_mappings' => [],
+ ]
+ )->assertSuccessful();
+
+ $template->refresh();
+ expect($template->page_manifest[0]['source_page'])->toBe(1);
+ expect($template->page_manifest[1]['source_page'])->toBeNull();
+ expect($template->page_manifest[2]['source_page'])->toBe(3);
+
+ // Export and verify page 3 has the 200mm-wide page, not the 120mm blank
+ $submission = $form->submissions()->create(['data' => ['name' => 'Test']]);
+ $service = new \App\Service\Pdf\PdfGeneratorService();
+ $resultPath = $service->generateFromTemplate($form, $submission, $template);
+ $content = Storage::get($resultPath);
+
+ $verifyTmp = tempnam(sys_get_temp_dir(), 'pdf_sizes_');
+ file_put_contents($verifyTmp, $content);
+ $verifyPdf = new \setasign\Fpdi\Fpdi();
+ $pageCount = $verifyPdf->setSourceFile($verifyTmp);
+ expect($pageCount)->toBe(3);
+
+ // Page 3 should have the 200mm-wide dimensions from original page 4
+ $tid = $verifyPdf->importPage(3);
+ $size = $verifyPdf->getTemplateSize($tid);
+ expect(round($size['width']))->toBe(200.0);
+ @unlink($verifyTmp);
+
+ // Second save with the renormalized manifest should also succeed
+ $response = $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => $template->page_manifest,
+ 'zone_mappings' => [],
+ ]
+ );
+ $response->assertSuccessful();
+
+ $template->refresh();
+ expect($template->page_manifest[0]['source_page'])->toBe(1);
+ expect($template->page_manifest[1]['source_page'])->toBeNull();
+ expect($template->page_manifest[2]['source_page'])->toBe(3);
+
+ // Export again after second save — page 3 dimensions must still match
+ $resultPath2 = $service->generateFromTemplate($form, $submission, $template->refresh());
+ $content2 = Storage::get($resultPath2);
+ $verifyTmp2 = tempnam(sys_get_temp_dir(), 'pdf_sizes2_');
+ file_put_contents($verifyTmp2, $content2);
+ $verifyPdf2 = new \setasign\Fpdi\Fpdi();
+ $verifyPdf2->setSourceFile($verifyTmp2);
+ $tid2 = $verifyPdf2->importPage(3);
+ $size2 = $verifyPdf2->getTemplateSize($tid2);
+ expect(round($size2['width']))->toBe(200.0);
+ @unlink($verifyTmp2);
+ });
+
+ it('exports correctly after page removal with zones on second page', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace, [
+ 'properties' => [
+ ['id' => 'name', 'name' => 'Name', 'type' => 'text'],
+ ],
+ ]);
+
+ $pdfContent = createMultiPagePdf(6);
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Export Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'export.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 6,
+ 'page_manifest' => PdfTemplate::buildDefaultPageManifest(6),
+ 'zone_mappings' => [],
+ ]);
+
+ // Save: keep pages 1 and 6, add a zone on page 2 (originally page 6)
+ $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => [
+ ['id' => 'p1', 'type' => 'source', 'source_page' => 1],
+ ['id' => 'p6', 'type' => 'source', 'source_page' => 6],
+ ],
+ 'zone_mappings' => [
+ [
+ 'id' => 'z1',
+ 'page_id' => 'p6',
+ 'x' => 10,
+ 'y' => 10,
+ 'width' => 30,
+ 'height' => 5,
+ 'field_id' => 'name',
+ 'font_size' => 12,
+ 'font_color' => '#000000',
+ ],
+ ],
+ ]
+ )->assertSuccessful();
+
+ $template->refresh();
+
+ // Generate PDF from this template
+ $submission = $form->submissions()->create([
+ 'data' => ['name' => 'John Doe'],
+ ]);
+
+ $service = new \App\Service\Pdf\PdfGeneratorService();
+ $resultPath = $service->generateFromTemplate($form, $submission, $template);
+
+ expect(Storage::exists($resultPath))->toBeTrue();
+ $content = Storage::get($resultPath);
+ expect($content)->toStartWith('%PDF');
+
+ // Verify the generated PDF has exactly 2 pages
+ $verifyPdf = new \setasign\Fpdi\Fpdi();
+ $verifyTmp = tempnam(sys_get_temp_dir(), 'pdf_verify_');
+ file_put_contents($verifyTmp, $content);
+ $pageCount = $verifyPdf->setSourceFile($verifyTmp);
+ @unlink($verifyTmp);
+
+ expect($pageCount)->toBe(2);
+ });
+});
+
/**
* Helper function to create a valid PDF using FPDF.
*/
@@ -716,3 +1022,27 @@ function createValidPdf(): string
return $pdf->Output('S');
}
+
+function createMultiPagePdf(int $pageCount): string
+{
+ $pdf = new \setasign\Fpdi\Fpdi();
+ $pdf->SetFont('Helvetica', '', 12);
+ for ($i = 1; $i <= $pageCount; $i++) {
+ $pdf->AddPage();
+ $pdf->Cell(0, 10, "Page {$i} Content");
+ }
+
+ return $pdf->Output('S');
+}
+
+function createMultiPagePdfWithSizes(array $pages): string
+{
+ $pdf = new \setasign\Fpdi\Fpdi();
+ $pdf->SetFont('Helvetica', '', 12);
+ foreach ($pages as $i => $page) {
+ $pdf->AddPage('P', [$page['w'], $page['h']]);
+ $pdf->Cell(0, 10, 'Page ' . ($i + 1));
+ }
+
+ return $pdf->Output('S');
+}