Skip to content

Beautiful Open-Source Form Builder

Implement PDF form field rendering and update PDF template creation l… (#1179)

Chirag Chhatralab8f27f58a589
diff --git a/api/app/Http/Controllers/Pdf/PdfTemplateController.php b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
index b68b00603..d16c3ae2f 100644
--- a/api/app/Http/Controllers/Pdf/PdfTemplateController.php
+++ b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
@@ -8,6 +8,7 @@ use App\Http\Requests\Pdf\CreatePdfTemplateRequest;
use App\Http\Requests\Pdf\UpdatePdfTemplateRequest;
use App\Models\Forms\Form;
use App\Models\PdfTemplate;
+use App\Service\Pdf\PdfFormFieldRenderer;
use App\Service\Pdf\PdfTemplateRebuildService;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@@ -61,13 +62,10 @@ class PdfTemplateController extends Controller
$originalFilename = $file->getClientOriginalName();
$message = 'PDF template uploaded successfully. Let\'s customize as per your needs.';
} else {
- $pdf = new Fpdi();
- $pdf->AddPage();
- $pdfContent = $pdf->Output('S');
-
- Storage::put($path, $pdfContent);
- $pageCount = 1;
- $fileSize = strlen($pdfContent);
+ $result = (new PdfFormFieldRenderer())->generate($form);
+ Storage::put($path, $result['pdf_content']);
+ $pageCount = $result['page_count'];
+ $fileSize = strlen($result['pdf_content']);
$originalFilename = $filename;
$message = 'PDF template created. Let\'s customize as per your needs.';
}
@@ -82,8 +80,8 @@ class PdfTemplateController extends Controller
'file_path' => $path,
'file_size' => $fileSize,
'page_count' => $pageCount,
- 'page_manifest' => PdfTemplate::buildDefaultPageManifest($pageCount),
- 'zone_mappings' => [],
+ 'page_manifest' => isset($result) ? $result['pages'] : PdfTemplate::buildDefaultPageManifest($pageCount),
+ 'zone_mappings' => isset($result) ? $result['zones'] : [],
'filename_pattern' => PdfTemplate::DEFAULT_FILENAME_PATTERN,
'remove_branding' => false,
]);
diff --git a/api/app/Service/Pdf/PdfFormFieldRenderer.php b/api/app/Service/Pdf/PdfFormFieldRenderer.php
new file mode 100644
index 000000000..a76a00510
--- /dev/null
+++ b/api/app/Service/Pdf/PdfFormFieldRenderer.php
@@ -0,0 +1,182 @@
+<?php
+
+namespace App\Service\Pdf;
+
+use App\Models\Forms\Form;
+use Illuminate\Support\Str;
+use setasign\Fpdi\Fpdi;
+
+class PdfFormFieldRenderer
+{
+ private const MARGIN_X = 5;
+ private const MARGIN_TOP = 4;
+ private const MARGIN_BOTTOM = 4;
+ private const FIELD_LABEL_HEIGHT = 2.5;
+ private const FIELD_VALUE_HEIGHT = 3;
+ private const FIELD_GAP = 0.5;
+ private const FIELD_SPACING = 1.5;
+ private const DEFAULT_FONT_SIZE = 12;
+ private const TITLE_ZONE_HEIGHT = 7;
+ private const TITLE_BASE_FONT_SIZE = 12;
+ private const REQUIRED_MARK_HTML = '<strong style="color: #EF4444">*</strong>';
+
+ private float $cursorY;
+ private int $currentPageNum = 0;
+ private array $pages = [];
+ private array $zones = [];
+ private string $currentPageId;
+
+ /**
+ * Build zone mappings and page manifest for a from-scratch PDF template.
+ *
+ * @return array{zones: array, pages: array, page_count: int, pdf_content: string}
+ */
+ public function generate(Form $form): array
+ {
+ $this->pages = [];
+ $this->zones = [];
+ $this->addPage();
+
+ // Form title as h1 static text zone
+ $title = htmlspecialchars($form->title ?? 'Untitled Form', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
+ $this->addStaticTextZone("<h1>{$title}</h1>", self::TITLE_ZONE_HEIGHT, fontSize: self::TITLE_BASE_FONT_SIZE);
+ $this->cursorY += 1;
+
+ $properties = collect($form->properties ?? [])
+ ->filter(fn ($field) => !str_starts_with($field['type'] ?? '', 'nf-'))
+ ->values();
+
+ foreach ($properties as $field) {
+ $estimatedHeight = $this->estimateFieldHeight($field);
+ if ($this->cursorY + $estimatedHeight > 100 - self::MARGIN_BOTTOM) {
+ $this->addPage();
+ }
+
+ $this->addFieldZones($field);
+ }
+
+ return [
+ 'zones' => $this->zones,
+ 'pages' => $this->pages,
+ 'page_count' => count($this->pages),
+ 'pdf_content' => $this->generateBlankPdf(count($this->pages)),
+ ];
+ }
+
+ private function addPage(): void
+ {
+ $this->currentPageNum++;
+ $this->currentPageId = (string) Str::uuid();
+ $this->pages[] = [
+ 'id' => $this->currentPageId,
+ 'type' => 'source',
+ 'source_page' => $this->currentPageNum,
+ ];
+ $this->cursorY = self::MARGIN_TOP;
+ }
+
+ private function addFieldZones(array $field): void
+ {
+ $type = $field['type'] ?? 'text';
+ $name = $field['name'] ?? 'Unnamed Field';
+ $fieldId = $field['id'] ?? null;
+ $required = !empty($field['required']);
+
+ // Label zone
+ $escapedName = htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
+ $label = $required ? $escapedName . ' ' . self::REQUIRED_MARK_HTML : $escapedName;
+ $this->addStaticTextZone($label, self::FIELD_LABEL_HEIGHT, fontSize: 10, fontColor: '#374151');
+
+ // Small gap between label and value
+ $this->cursorY += self::FIELD_GAP;
+
+ if (!$fieldId) {
+ return;
+ }
+
+ // Value zone
+ $zoneHeight = $this->getFieldZoneHeight($type, $field);
+ $this->addFieldValueZone($fieldId, $zoneHeight);
+
+ // Spacing before next field
+ $this->cursorY += self::FIELD_SPACING;
+ }
+
+ private function addStaticTextZone(string $text, float $height, int $fontSize = self::DEFAULT_FONT_SIZE, string $fontColor = '#000000'): void
+ {
+ $this->zones[] = [
+ 'id' => (string) Str::uuid(),
+ 'page' => $this->currentPageNum,
+ 'page_id' => $this->currentPageId,
+ 'x' => self::MARGIN_X,
+ 'y' => $this->cursorY,
+ 'width' => 100 - (2 * self::MARGIN_X),
+ 'height' => $height,
+ 'static_text' => $text,
+ 'font_size' => $fontSize,
+ 'font_color' => $fontColor,
+ ];
+ $this->cursorY += $height;
+ }
+
+ private function addFieldValueZone(string $fieldId, float $height): void
+ {
+ $this->zones[] = [
+ 'id' => (string) Str::uuid(),
+ 'page' => $this->currentPageNum,
+ 'page_id' => $this->currentPageId,
+ 'x' => self::MARGIN_X,
+ 'y' => $this->cursorY,
+ 'width' => 100 - (2 * self::MARGIN_X),
+ 'height' => $height,
+ 'field_id' => $fieldId,
+ 'font_size' => self::DEFAULT_FONT_SIZE,
+ 'font_color' => '#111827',
+ ];
+ $this->cursorY += $height;
+ }
+
+ private function getFieldZoneHeight(string $type, array $field): float
+ {
+ return match ($type) {
+ 'text' => !empty($field['multi_lines']) ? 10 : self::FIELD_VALUE_HEIGHT,
+ 'rich_text' => 10,
+ 'signature' => 10,
+ 'files' => 8,
+ 'matrix' => min(5 + count($field['rows'] ?? []) * 3, 20),
+ 'multi_select' => min(4 + count($this->getSelectOptionCount($field)) * 2, 14),
+ default => self::FIELD_VALUE_HEIGHT,
+ };
+ }
+
+ private function estimateFieldHeight(array $field): float
+ {
+ $type = $field['type'] ?? 'text';
+
+ return self::FIELD_LABEL_HEIGHT + self::FIELD_GAP + $this->getFieldZoneHeight($type, $field) + self::FIELD_SPACING;
+ }
+
+ private function getSelectOptionCount(array $field): array
+ {
+ $options = $field['multi_select'] ?? $field['select'] ?? [];
+ if (!is_array($options)) {
+ return [];
+ }
+
+ if (isset($options['options'])) {
+ $options = $options['options'];
+ }
+
+ return is_array($options) ? $options : [];
+ }
+
+ private function generateBlankPdf(int $pageCount): string
+ {
+ $pdf = new Fpdi();
+ for ($i = 0; $i < $pageCount; $i++) {
+ $pdf->AddPage();
+ }
+
+ return $pdf->Output('S');
+ }
+}
diff --git a/api/app/Service/Pdf/PdfRichTextRenderer.php b/api/app/Service/Pdf/PdfRichTextRenderer.php
index dee1530dd..3862d8a8b 100644
--- a/api/app/Service/Pdf/PdfRichTextRenderer.php
+++ b/api/app/Service/Pdf/PdfRichTextRenderer.php
@@ -27,7 +27,6 @@ class PdfRichTextRenderer
): void {
$baseFontSize = (int) ($zone['font_size'] ?? self::DEFAULT_FONT_SIZE);
$baseColor = $this->colorParser->parseColor($zone['font_color'] ?? null);
- $lineHeight = $baseFontSize * 0.4;
$zoneBottom = $y + $height;
// Set margins so text wraps inside the zone width.
@@ -44,6 +43,7 @@ class PdfRichTextRenderer
$pdf->SetXY($x, $y);
$segments = $this->parseHtmlToSegments($text, $baseFontSize, $baseColor);
+ $currentLineX = $x;
foreach ($segments as $segment) {
if ($pdf->GetY() >= $zoneBottom) {
@@ -53,6 +53,7 @@ class PdfRichTextRenderer
$style = ($segment['bold'] ? 'B' : '') . ($segment['italic'] ? 'I' : '') . ($segment['underline'] ? 'U' : '');
$fontSize = $segment['fontSize'];
$color = $segment['color'];
+ $lineHeight = $fontSize * 0.4;
$pdf->SetFont('Helvetica', $style, $fontSize);
$pdf->SetTextColor(...$color);
@@ -63,10 +64,11 @@ class PdfRichTextRenderer
}
$pdf->Ln($lineHeight);
$pdf->SetX($x);
+ $currentLineX = $x;
}
if ($segment['text'] !== '') {
- $this->writeClipped($pdf, $segment['text'], $lineHeight, $width, $x, $zoneBottom);
+ $this->writeInlineClipped($pdf, $segment['text'], $lineHeight, $width, $x, $currentLineX, $zoneBottom);
}
}
@@ -74,45 +76,54 @@ class PdfRichTextRenderer
$pdf->SetRightMargin($savedRightMargin);
}
- private function writeClipped(Fpdi $pdf, string $text, float $lineHeight, float $width, float $x, float $zoneBottom): void
+ private function writeInlineClipped(Fpdi $pdf, string $text, float $lineHeight, float $width, float $x, float &$currentLineX, float $zoneBottom): void
{
- $lines = $this->wrapTextToLines($pdf, $text, $width);
- foreach ($lines as $line) {
- if ($pdf->GetY() + $lineHeight > $zoneBottom) {
- break;
+ $paragraphs = explode("\n", str_replace("\r", '', $text));
+ foreach ($paragraphs as $paragraphIndex => $paragraph) {
+ if ($paragraphIndex > 0) {
+ if (!$this->moveToNextLine($pdf, $lineHeight, $x, $currentLineX, $zoneBottom)) {
+ return;
+ }
}
- $pdf->Cell($width, $lineHeight, $line, 0, 2, '', false);
- $pdf->SetX($x);
- }
- }
- private function wrapTextToLines(Fpdi $pdf, string $text, float $width): array
- {
- $text = str_replace("\r", '', $text);
- $lines = [];
- $paragraphs = explode("\n", $text);
- $usableWidth = max(1, $width - 2);
-
- foreach ($paragraphs as $para) {
- $words = explode(' ', $para);
- $currentLine = '';
- foreach ($words as $word) {
- $testLine = $currentLine === '' ? $word : $currentLine . ' ' . $word;
- if ($pdf->GetStringWidth($testLine) <= $usableWidth) {
- $currentLine = $testLine;
- } else {
- if ($currentLine !== '') {
- $lines[] = $currentLine;
+ $tokens = preg_split('/(\s+)/u', $paragraph, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
+ foreach ($tokens ?: [] as $token) {
+ if (trim($token) === '' && $currentLineX === $x) {
+ continue;
+ }
+
+ $tokenWidth = $pdf->GetStringWidth($token);
+ if ($currentLineX > $x && $currentLineX + $tokenWidth > $x + $width) {
+ if (!$this->moveToNextLine($pdf, $lineHeight, $x, $currentLineX, $zoneBottom)) {
+ return;
+ }
+ if (trim($token) === '') {
+ continue;
}
- $currentLine = $word;
}
- }
- if ($currentLine !== '') {
- $lines[] = $currentLine;
+
+ if ($pdf->GetY() + $lineHeight > $zoneBottom) {
+ return;
+ }
+
+ $pdf->SetX($currentLineX);
+ $pdf->Cell($tokenWidth, $lineHeight, $token, 0, 0, '', false);
+ $currentLineX += $tokenWidth;
}
}
+ }
+
+ private function moveToNextLine(Fpdi $pdf, float $lineHeight, float $x, float &$currentLineX, float $zoneBottom): bool
+ {
+ if ($pdf->GetY() + $lineHeight > $zoneBottom) {
+ return false;
+ }
+
+ $pdf->Ln($lineHeight);
+ $pdf->SetX($x);
+ $currentLineX = $x;
- return $lines;
+ return true;
}
private function parseHtmlToSegments(string $html, int $baseFontSize, array $baseColor): array
@@ -180,7 +191,7 @@ class PdfRichTextRenderer
$name = strtolower($node->nodeName);
- $isBold = $bold || in_array($name, ['strong', 'b'], true);
+ $isBold = $bold || in_array($name, ['strong', 'b', 'h1', 'h2'], true);
$isItalic = $italic || in_array($name, ['em', 'i'], true);
$isUnderline = $underline || $name === 'u';
diff --git a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
index af843ee75..64c540ea3 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
@@ -385,6 +385,60 @@ describe('PdfContentRenderer scalar values', function () {
expect($richTextRenderer->rendered)->toBeFalse();
});
+
+ it('renders inline rich text segments without dropping styled required marks', function () {
+ $renderer = new PdfRichTextRenderer();
+ $pdf = new class () extends Fpdi {
+ public array $cells = [];
+ private array $currentColor = [0, 0, 0];
+ private string $currentStyle = '';
+
+ public function SetTextColor($r, $g = null, $b = null)
+ {
+ $this->currentColor = [(int) $r, (int) $g, (int) $b];
+ parent::SetTextColor($r, $g, $b);
+ }
+
+ public function SetFont($family, $style = '', $size = 0)
+ {
+ $this->currentStyle = $style;
+ parent::SetFont($family, $style, $size);
+ }
+
+ public function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
+ {
+ $this->cells[] = [
+ 'text' => $txt,
+ 'x' => $this->GetX(),
+ 'y' => $this->GetY(),
+ 'color' => $this->currentColor,
+ 'style' => $this->currentStyle,
+ ];
+ parent::Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
+ }
+ };
+ $pdf->AddPage();
+
+ $renderer->render(
+ $pdf,
+ 'Name <strong style="color: #EF4444">*</strong>',
+ 10,
+ 10,
+ 80,
+ 8,
+ ['font_size' => 10, 'font_color' => '#374151'],
+ 210
+ );
+
+ $nameCell = collect($pdf->cells)->firstWhere('text', 'Name');
+ $starCell = collect($pdf->cells)->firstWhere('text', '*');
+
+ expect($nameCell)->not->toBeNull();
+ expect($starCell)->not->toBeNull();
+ expect($starCell['y'])->toBe($nameCell['y']);
+ expect($starCell['color'])->toBe([239, 68, 68]);
+ expect($starCell['style'])->toContain('B');
+ });
});
/**
diff --git a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
index d079ba461..19042a8a3 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
@@ -115,10 +115,13 @@ describe('PDF Template Upload', function () {
});
describe('PDF Template Create from Scratch', function () {
- it('can create a template with 1 blank page', function () {
+ it('can create a template from scratch with form fields rendered', function () {
$user = $this->actingAsProUser();
$workspace = $this->createUserWorkspace($user);
$form = $this->createForm($user, $workspace);
+ $properties = $form->properties;
+ $properties[0]['required'] = true;
+ $form->update(['properties' => $properties]);
$response = $this->postJson(route('open.forms.pdf-templates.store', $form), []);
@@ -141,9 +144,38 @@ describe('PDF Template Create from Scratch', function () {
$template = PdfTemplate::where('form_id', $form->id)->first();
expect($template->name)->toBe('My PDF Template 1');
- expect($template->page_count)->toBe(1);
- expect($template->zone_mappings)->toBe([]);
+ expect($template->page_count)->toBeGreaterThanOrEqual(1);
+ expect($template->zone_mappings)->toBeArray()->not->toBeEmpty();
expect(Storage::exists($template->file_path))->toBeTrue();
+
+ $titleZone = collect($template->zone_mappings)
+ ->first(fn ($zone) => isset($zone['static_text']) && str_contains($zone['static_text'], '<h1>'));
+ expect($titleZone)->not->toBeNull();
+ expect($titleZone['static_text'])->toBe('<h1>' . e($form->title) . '</h1>');
+
+ $requiredLabelZone = collect($template->zone_mappings)
+ ->first(fn ($zone) => ($zone['static_text'] ?? null) === 'Name <strong style="color: #EF4444">*</strong>');
+ expect($requiredLabelZone)->not->toBeNull();
+
+ // Each form input field should have a field_id zone
+ $inputFields = collect($form->properties)
+ ->filter(fn ($f) => !str_starts_with($f['type'], 'nf-'))
+ ->pluck('id')
+ ->toArray();
+ $zoneFieldIds = collect($template->zone_mappings)
+ ->pluck('field_id')
+ ->filter()
+ ->values()
+ ->toArray();
+ foreach ($inputFields as $fieldId) {
+ expect($zoneFieldIds)->toContain($fieldId);
+ }
+
+ // Every zone must reference a valid page_id from the manifest
+ $manifestIds = collect($template->page_manifest)->pluck('id')->toArray();
+ foreach ($template->zone_mappings as $zone) {
+ expect($manifestIds)->toContain($zone['page_id']);
+ }
});
it('uses incremental default name when creating from scratch', function () {
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index 8f8a212c7..c15a81e9d 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -355,6 +355,12 @@ const saveFormEdit = () => {
const saveFormCreate = () => {
if (form.value.busy) return
+
+ if (!workspace.value?.id) {
+ useAlert().error("Your workspace is still loading, please try again.")
+ return
+ }
+
// Attach workspace ID before sending
form.value.workspace_id = workspace.value.id
validationErrorResponse.value = null
diff --git a/client/components/open/forms/components/FormEditorNavbar.vue b/client/components/open/forms/components/FormEditorNavbar.vue
index 3ec0e9214..d8d47c510 100644
--- a/client/components/open/forms/components/FormEditorNavbar.vue
+++ b/client/components/open/forms/components/FormEditorNavbar.vue
@@ -1,5 +1,5 @@
<template>
- <div class="w-full border-b p-2 flex gap-x-2 items-center bg-white">
+ <div class="w-full border-b px-3 py-3 min-h-16 flex gap-x-3 items-center bg-white">
<a
v-if="backButton"
href="#"
@@ -41,13 +41,13 @@
class="ml-2"
/>
- <div class="flex-grow flex justify-center gap-2">
+ <div class="flex-grow min-w-0 flex justify-center items-center gap-2">
<EditableTag
id="form-editor-title"
v-model="form.title"
- element="h3"
+ element="h1"
:max-length="255"
- class="font-medium py-1 text-md w-48 text-neutral-500 truncate form-editor-title"
+ class="font-semibold py-1 text-xl leading-7 w-72 max-w-full text-neutral-700 truncate form-editor-title"
/>
<UBadge
v-if="form.visibility == 'draft'"
diff --git a/client/components/open/pdf-editor/PdfRightSidebar.vue b/client/components/open/pdf-editor/PdfRightSidebar.vue
index a2267aeb8..fa5f54d60 100644
--- a/client/components/open/pdf-editor/PdfRightSidebar.vue
+++ b/client/components/open/pdf-editor/PdfRightSidebar.vue
@@ -155,21 +155,24 @@
</div>
<!-- Zones list -->
- <div v-else class="rounded-md border border-neutral-300">
+ <div v-else class="rounded-md border border-neutral-300 dark:border-neutral-700 divide-y divide-neutral-200 dark:divide-neutral-700 overflow-hidden">
<div
v-for="zone in currentPageZones"
:key="zone.id"
- class="flex items-center justify-between gap-2 p-3 transition-colors cursor-pointer border-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-700"
- :class="{
- 'border-b': zone !== currentPageZones[currentPageZones.length - 1]
- }"
+ class="flex items-center justify-between gap-2 px-2 py-2 transition-colors cursor-pointer hover:bg-neutral-100 dark:hover:bg-neutral-700"
@click="pdfStore.setSelectedZone(zone.id)"
>
- <div class="min-w-0 flex-1">
+ <div class="shrink-0 w-7 h-7 rounded-md bg-neutral-100 dark:bg-neutral-700 flex items-center justify-center">
+ <UIcon
+ :name="getZoneIcon(zone)"
+ class="w-4 h-4 text-neutral-500 dark:text-neutral-300"
+ />
+ </div>
+ <div class="min-w-0 flex-1 leading-none">
<p class="text-sm font-medium text-neutral-900 dark:text-white truncate">
- {{ getZoneLabel(zone) }}
+ {{ getZoneListLabel(zone) }}
</p>
- <p class="text-xs text-neutral-500 dark:text-neutral-400 mt-0.5">
+ <p class="text-[11px] text-neutral-500 dark:text-neutral-400 mt-1">
Page {{ zone.page }} • {{ zone.font_size }}px
</p>
</div>
@@ -180,7 +183,7 @@
>
<Icon
name="heroicons:cog-8-tooth-solid"
- class="h-5 w-5"
+ class="h-4 w-4"
/>
</button>
</UTooltip>
@@ -262,13 +265,47 @@ const addZoneMenuItems = computed(() => {
const selectedZoneLabel = computed(() => {
if (!selectedZone.value) return ''
- return getZoneLabel(selectedZone.value)
+ return getZoneListLabel(selectedZone.value)
})
const goBackToZones = () => {
pdfStore.setSelectedZone(null)
}
+const decodeTextEntities = (value) => {
+ return value
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#039;/g, "'")
+}
+
+const getStaticTextPreview = (zone) => {
+ const text = decodeTextEntities(
+ String(zone.static_text || '')
+ .replace(/<br\s*\/?>/gi, ' ')
+ .replace(/<\/(p|div|h1|h2|h3|h4|h5|h6|li)>/gi, ' ')
+ .replace(/<[^>]*>/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ )
+
+ return text || 'Empty static text'
+}
+
+const getZoneListLabel = (zone) => {
+ if (zone.static_text !== undefined) return getStaticTextPreview(zone)
+ return getZoneLabel(zone)
+}
+
+const getZoneIcon = (zone) => {
+ if (zone.static_text !== undefined) return 'i-heroicons-document-text'
+ if (zone.static_image !== undefined) return 'i-heroicons-photo'
+ return 'i-heroicons-at-symbol'
+}
+
const richTextOptions = {
formats: ['bold', 'italic', 'underline', 'header', 'color'],
modules: {
diff --git a/client/components/open/pdf-editor/PdfZoneEditor.vue b/client/components/open/pdf-editor/PdfZoneEditor.vue
index 787c3b4cb..26a76d494 100644
--- a/client/components/open/pdf-editor/PdfZoneEditor.vue
+++ b/client/components/open/pdf-editor/PdfZoneEditor.vue
@@ -63,7 +63,8 @@
<!-- In-canvas text preview (static text zones only) -->
<div
v-if="zone.static_text !== undefined && zone.static_text"
- class="w-full h-full overflow-hidden leading-tight pointer-events-none select-none"
+ class="pdf-zone-text-preview w-full h-full overflow-hidden leading-tight pointer-events-none select-none"
+ :style="getZoneTextPreviewStyle(zone)"
v-html="zone.static_text"
/>
<!-- In-canvas image preview (static image zones only) -->
@@ -77,11 +78,29 @@
class="w-full h-full"
>
</div>
+ <!-- In-canvas mapped field preview (actual submissions render here) -->
+ <div
+ v-else-if="zone.field_id"
+ class="pdf-zone-text-preview w-full h-full overflow-hidden pointer-events-none select-none leading-tight"
+ :style="getZoneTextPreviewStyle(zone)"
+ >
+ {{ getZoneLabel(zone) }}
+ </div>
<div
class="absolute bottom-0 right-0 w-3 h-3 bg-blue-500 cursor-se-resize"
@mousedown.stop="startResizing($event, zone)"
/>
</div>
+ <div
+ v-if="snapGuides.page === pageNum && snapGuides.vertical !== null"
+ class="absolute top-0 bottom-0 w-px bg-blue-500/80 pointer-events-none z-20"
+ :style="{ left: `${snapGuides.vertical}%` }"
+ />
+ <div
+ v-if="snapGuides.page === pageNum && snapGuides.horizontal !== null"
+ class="absolute left-0 right-0 h-px bg-blue-500/80 pointer-events-none z-20"
+ :style="{ top: `${snapGuides.horizontal}%` }"
+ />
</div>
<!-- Page number label below -->
<span class="mt-1 text-xs text-neutral-500 dark:text-neutral-400">
@@ -125,6 +144,11 @@ const activeRenderTasks = new Map()
const renderPassId = ref(0)
const zoomRenderTimeout = ref(null)
const pendingRenderAfterInteraction = ref(false)
+const INITIAL_FIT_HORIZONTAL_PADDING = 48
+const SNAP_THRESHOLD_PX = 6
+const MIN_ZONE_WIDTH_PERCENT = 5
+const MIN_ZONE_HEIGHT_PERCENT = 2
+const snapGuides = ref({ page: null, vertical: null, horizontal: null })
// Drag/resize state
const isDragging = ref(false)
@@ -160,6 +184,15 @@ const getZoneStyle = (zone) => {
}
}
+const getZoneTextPreviewStyle = (zone) => {
+ const fontSize = Number(zone.font_size) || 12
+ return {
+ color: zone.font_color || '#111827',
+ fontFamily: 'Helvetica, Arial, sans-serif',
+ fontSize: `${fontSize * zoomScale.value}px`,
+ }
+}
+
const setCanvasRef = (el, pageNum) => {
if (el) {
canvasRefs.value[pageNum] = el
@@ -199,6 +232,146 @@ const getActiveZoneLive = () => {
return pdfTemplate.value.zone_mappings.find((z) => z.id === activeZone.value.id) || null
}
+const clearSnapGuides = () => {
+ snapGuides.value = { page: null, vertical: null, horizontal: null }
+}
+
+const setSnapGuides = (page, snapResult) => {
+ snapGuides.value = {
+ page,
+ vertical: snapResult.vertical ?? null,
+ horizontal: snapResult.horizontal ?? null,
+ }
+}
+
+const clampPercent = (value, min, max) => {
+ return Math.max(min, Math.min(max, value))
+}
+
+const getSnapTargetsForPage = (activeZoneId, page) => {
+ const targets = {
+ x: [0, 50, 100],
+ y: [0, 50, 100],
+ }
+
+ for (const zone of pdfTemplate.value?.zone_mappings || []) {
+ if (zone.id === activeZoneId || Number(zone.page) !== Number(page)) continue
+ targets.x.push(zone.x, zone.x + (zone.width / 2), zone.x + zone.width)
+ targets.y.push(zone.y, zone.y + (zone.height / 2), zone.y + zone.height)
+ }
+
+ return targets
+}
+
+const findClosestSnap = (activeAnchors, targets, thresholdPercent) => {
+ let closest = null
+
+ for (const activeAnchor of activeAnchors) {
+ for (const target of targets) {
+ const delta = target - activeAnchor
+ const distance = Math.abs(delta)
+ if (distance > thresholdPercent) continue
+ if (!closest || distance < closest.distance) {
+ closest = { delta, target, distance }
+ }
+ }
+ }
+
+ return closest
+}
+
+const snapMovingZone = (zone, rect, dimensions) => {
+ const targets = getSnapTargetsForPage(zone.id, zone.page)
+ const thresholdX = (SNAP_THRESHOLD_PX / dimensions.w) * 100
+ const thresholdY = (SNAP_THRESHOLD_PX / dimensions.h) * 100
+
+ const xSnap = findClosestSnap([
+ rect.x,
+ rect.x + (rect.width / 2),
+ rect.x + rect.width,
+ ], targets.x, thresholdX)
+ const ySnap = findClosestSnap([
+ rect.y,
+ rect.y + (rect.height / 2),
+ rect.y + rect.height,
+ ], targets.y, thresholdY)
+
+ const snappedRect = { ...rect }
+ if (xSnap) {
+ snappedRect.x = clampPercent(rect.x + xSnap.delta, 0, 100 - rect.width)
+ }
+ if (ySnap) {
+ snappedRect.y = clampPercent(rect.y + ySnap.delta, 0, 100 - rect.height)
+ }
+
+ return {
+ rect: snappedRect,
+ vertical: xSnap?.target,
+ horizontal: ySnap?.target,
+ }
+}
+
+const findResizeSnap = (start, currentSize, targets, thresholdPercent, minSize, maxSize) => {
+ const anchors = [
+ {
+ value: start + currentSize,
+ getSize: (target) => target - start,
+ },
+ {
+ value: start + (currentSize / 2),
+ getSize: (target) => (target - start) * 2,
+ },
+ ]
+ let closest = null
+
+ for (const anchor of anchors) {
+ for (const target of targets) {
+ const nextSize = anchor.getSize(target)
+ if (nextSize < minSize || nextSize > maxSize) continue
+ const delta = target - anchor.value
+ const distance = Math.abs(delta)
+ if (distance > thresholdPercent) continue
+ if (!closest || distance < closest.distance) {
+ closest = { size: nextSize, target, distance }
+ }
+ }
+ }
+
+ return closest
+}
+
+const snapResizingZone = (zone, rect, dimensions) => {
+ const targets = getSnapTargetsForPage(zone.id, zone.page)
+ const thresholdX = (SNAP_THRESHOLD_PX / dimensions.w) * 100
+ const thresholdY = (SNAP_THRESHOLD_PX / dimensions.h) * 100
+ const widthSnap = findResizeSnap(
+ rect.x,
+ rect.width,
+ targets.x,
+ thresholdX,
+ MIN_ZONE_WIDTH_PERCENT,
+ 100 - rect.x
+ )
+ const heightSnap = findResizeSnap(
+ rect.y,
+ rect.height,
+ targets.y,
+ thresholdY,
+ MIN_ZONE_HEIGHT_PERCENT,
+ 100 - rect.y
+ )
+
+ return {
+ rect: {
+ ...rect,
+ width: widthSnap?.size ?? rect.width,
+ height: heightSnap?.size ?? rect.height,
+ },
+ vertical: widthSnap?.target,
+ horizontal: heightSnap?.target,
+ }
+}
+
// Initialize PDF.js library
const initPdfJs = async () => {
if (!import.meta.client) return null
@@ -231,6 +404,35 @@ const getPriorityZoomPages = () => {
return candidatePages.filter((pageNum) => pageList.value.includes(pageNum) && !isNewPage(pageNum))
}
+const getEditorScrollRoot = () => {
+ return pagesContainer.value?.closest?.('.pdf-editor-scroll-container')
+}
+
+const getAvailablePageWidth = () => {
+ const scrollRoot = getEditorScrollRoot()
+ const containerWidth = scrollRoot?.clientWidth || pagesContainer.value?.clientWidth || 0
+ return Math.max(0, containerWidth - INITIAL_FIT_HORIZONTAL_PADDING)
+}
+
+const fitZoomToPageWidth = async () => {
+ if (!pdfDoc.value) return
+
+ const firstPhysicalPage = pageList.value.find((pageNum) => !isNewPage(pageNum))
+ if (!firstPhysicalPage) return
+
+ const sourcePageNumber = pdfStore.getSourcePageNumber(firstPhysicalPage)
+ if (sourcePageNumber == null) return
+
+ const availablePageWidth = getAvailablePageWidth()
+ if (!availablePageWidth) return
+
+ const page = await pdfDoc.value.getPage(sourcePageNumber)
+ const viewport = page.getViewport({ scale: 1 })
+ if (!viewport.width) return
+
+ pdfStore.setZoomScale(availablePageWidth / viewport.width)
+}
+
const scheduleRenderAllPages = (delayMs = 0, options = {}) => {
if (!pdfDoc.value) return
const { zoomOnlyVisible = false } = options
@@ -271,6 +473,8 @@ const loadPdf = async () => {
formsApi.pdfTemplates.getDownloadRequest(form.value.id, pdfTemplate.value.id)
)
pdfDoc.value = await loadingTask.promise
+ await nextTick()
+ await fitZoomToPageWidth()
await renderAllPages()
} catch (err) {
console.error('Failed to load PDF:', err)
@@ -448,7 +652,7 @@ const setupObserver = () => {
if (intersectionObserver) {
intersectionObserver.disconnect()
}
- const scrollRoot = pagesContainer.value?.closest?.('.pdf-editor-scroll-container')
+ const scrollRoot = getEditorScrollRoot()
if (!scrollRoot || Object.keys(pageRefs.value).length === 0) return
intersectionObserver = new IntersectionObserver(
@@ -530,6 +734,7 @@ const moveZoneToAdjacentPage = (direction, event) => {
const targetPageNum = pageList.value[targetIndex]
zone.page = targetPageNum
zone.page_id = pdfStore.getPageId(targetPageNum)
+ clearSnapGuides()
zone.y = direction > 0
? 0
: Math.max(0, 100 - zone.height)
@@ -572,17 +777,17 @@ const onDrag = (event) => {
}
}
- const { w, h } = getCanvasDimensions()
- if (!Number.isFinite(w) || !Number.isFinite(h) || w < 20 || h < 20) return
+ const dimensions = getCanvasDimensions()
+ if (!Number.isFinite(dimensions.w) || !Number.isFinite(dimensions.h) || dimensions.w < 20 || dimensions.h < 20) return
const dx = event.clientX - dragStart.value.x
const dy = event.clientY - dragStart.value.y
- const dxPercent = (dx / w) * 100
- const dyPercent = (dy / h) * 100
+ const dxPercent = (dx / dimensions.w) * 100
+ const dyPercent = (dy / dimensions.h) * 100
const maxY = 100 - zoneStart.value.height
- let newX = Math.max(0, Math.min(100 - zoneStart.value.width, zoneStart.value.x + dxPercent))
- let newY = Math.max(0, Math.min(maxY, zoneStart.value.y + dyPercent))
+ let newX = clampPercent(zoneStart.value.x + dxPercent, 0, 100 - zoneStart.value.width)
+ let newY = clampPercent(zoneStart.value.y + dyPercent, 0, maxY)
// If dragged down while already clamped at bottom edge, transfer to next page early.
if (pointerDeltaY > 0 && newY >= maxY && moveZoneToAdjacentPage(1, event)) {
@@ -595,14 +800,23 @@ const onDrag = (event) => {
return
}
- zone.x = newX
- zone.y = newY
+ const snapResult = snapMovingZone(zone, {
+ x: newX,
+ y: newY,
+ width: zoneStart.value.width,
+ height: zoneStart.value.height,
+ }, dimensions)
+
+ zone.x = snapResult.rect.x
+ zone.y = snapResult.rect.y
+ setSnapGuides(zone.page, snapResult)
}
// Stop dragging
const stopDragging = () => {
isDragging.value = false
activeZone.value = null
+ clearSnapGuides()
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDragging)
}
@@ -624,25 +838,42 @@ const startResizing = (event, zone) => {
const onResize = (event) => {
const zone = getActiveZoneLive()
if (!isResizing.value || !zone) return
- const { w, h } = getCanvasDimensions()
- if (!Number.isFinite(w) || !Number.isFinite(h) || w < 20 || h < 20) return
+ const dimensions = getCanvasDimensions()
+ if (!Number.isFinite(dimensions.w) || !Number.isFinite(dimensions.h) || dimensions.w < 20 || dimensions.h < 20) return
const dx = event.clientX - dragStart.value.x
const dy = event.clientY - dragStart.value.y
- const dxPercent = (dx / w) * 100
- const dyPercent = (dy / h) * 100
+ const dxPercent = (dx / dimensions.w) * 100
+ const dyPercent = (dy / dimensions.h) * 100
- let newWidth = Math.max(5, Math.min(100 - zoneStart.value.x, zoneStart.value.width + dxPercent))
- let newHeight = Math.max(2, Math.min(100 - zoneStart.value.y, zoneStart.value.height + dyPercent))
+ let newWidth = clampPercent(
+ zoneStart.value.width + dxPercent,
+ MIN_ZONE_WIDTH_PERCENT,
+ 100 - zoneStart.value.x
+ )
+ let newHeight = clampPercent(
+ zoneStart.value.height + dyPercent,
+ MIN_ZONE_HEIGHT_PERCENT,
+ 100 - zoneStart.value.y
+ )
- zone.width = newWidth
- zone.height = newHeight
+ const snapResult = snapResizingZone(zone, {
+ x: zoneStart.value.x,
+ y: zoneStart.value.y,
+ width: newWidth,
+ height: newHeight,
+ }, dimensions)
+
+ zone.width = snapResult.rect.width
+ zone.height = snapResult.rect.height
+ setSnapGuides(zone.page, snapResult)
}
// Stop resizing
const stopResizing = () => {
isResizing.value = false
activeZone.value = null
+ clearSnapGuides()
document.removeEventListener('mousemove', onResize)
document.removeEventListener('mouseup', stopResizing)
}
@@ -677,6 +908,7 @@ watch(lastAddedZoneId, async (zoneId) => {
onUnmounted(() => {
cancelAllRenderTasks()
+ clearSnapGuides()
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDragging)
document.removeEventListener('mousemove', onResize)
@@ -701,4 +933,24 @@ onUnmounted(() => {
.pdf-zone-editor {
position: relative;
}
+
+.pdf-zone-text-preview :deep(h1),
+.pdf-zone-text-preview :deep(h2),
+.pdf-zone-text-preview :deep(h3),
+.pdf-zone-text-preview :deep(p),
+.pdf-zone-text-preview :deep(div) {
+ margin: 0;
+}
+
+.pdf-zone-text-preview :deep(h1) {
+ font-size: 2em;
+ font-weight: 700;
+ line-height: 1;
+}
+
+.pdf-zone-text-preview :deep(h2) {
+ font-size: 1.5em;
+ font-weight: 700;
+ line-height: 1;
+}
</style>
diff --git a/client/pages/forms/[slug]/show/pdf-templates.vue b/client/pages/forms/[slug]/show/pdf-templates.vue
index f9d80a40f..5ac6de5b5 100644
--- a/client/pages/forms/[slug]/show/pdf-templates.vue
+++ b/client/pages/forms/[slug]/show/pdf-templates.vue
@@ -67,12 +67,12 @@
class="h-5 w-5 text-primary-600"
/>
</div>
- <div>
+ <div class="min-w-0">
<h3 class="font-medium text-neutral-900">
{{ template.name }}
</h3>
- <p class="text-sm text-neutral-500">
- {{ template.original_filename }} •
+ <p class="text-sm text-neutral-500 truncate">
+ Format: {{ getFilenamePatternPreview(template) }}.pdf •
{{ template.page_count }} page{{ template.page_count > 1 ? 's' : '' }} •
{{ template.zone_mappings?.length || 0 }} zone{{ template.zone_mappings?.length >= 1 ? 's' : '' }}
</p>
@@ -166,6 +166,29 @@ const deleteTemplate = remove(() => props.form?.id)
const templates = computed(() => templatesData.value?.data || [])
+const decodeTextEntities = (value) => {
+ return value
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#039;/g, "'")
+}
+
+const getFilenamePatternPreview = (template) => {
+ const pattern = template.filename_pattern || template.original_filename || template.filename || 'PDF template'
+ return decodeTextEntities(
+ String(pattern)
+ .replace(/<span[^>]*mention-field-name="([^"]*)"[^>]*>.*?<\/span>/gi, '$1')
+ .replace(/<span[^>]*>(.*?)<\/span>/gi, '$1')
+ .replace(/<[^>]*>/g, '')
+ .replace(/\.pdf$/i, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ ) || 'PDF template'
+}
+
// Create menu items (Upload PDF, Create from scratch)
const createMenuItems = [
[