# Portwood 3.65.0 authoring and workflow context Use this reference with the data shape from Copy AI Prompt. Ask for the template type, output format, generation entry point, selected fields and relationship aliases. For signing, ask for the roles, audience and delivery route. Use fictional values for examples. Preserve existing bindings on edits. For an HTML task return a complete printable HTML body, with separate Header HTML and Footer HTML when applicable. For a Flow task return a sequence of elements with input and output mappings, fault and pending branches, and a visible completion check. A template carries content. Flow handles navigation, events, and delivery. # Portwood HTML template recipes Use these as small authoring patterns when authoring an HTML template for Salesforce PDF output. Keep the HTML simple, use the exact field API names from the template query, and verify the generated PDF in the target org. For the full renderer rules and reusable LLM prompt, see [HTML and Word layout](template-layout.md). Start with the [one-field letter](../knowledgebase/examples/acceptance/account-letter.html). For a full working example, use the [service schedule](../knowledgebase/examples/acceptance/service-review.html) and its [rendered PDF](../knowledgebase/examples/acceptance/service-review.pdf). ## Two-column header Use a table for side-by-side content. Fixed widths and cell padding are more predictable than flexbox or grid. ```html
{Account.Name}
{Account.BillingStreet}
{Account.BillingCity}, {Account.BillingState} {Account.BillingPostalCode}
Quote {Name}
Prepared {Today:MMMM d, yyyy}
{RunningUser.Name}
``` ## Repeating line items with totals Put the opening and closing loop tags inside the first and last cells of the repeating row. The table header stays in place while the data row repeats. ```html
Item Qty Price Total
{#OpportunityLineItems}{Product2.Name} {Quantity} {UnitPrice:currency} {TotalPrice:currency}{/OpportunityLineItems}

Total: {Amount:currency}

``` For a row number, place `{RowNumber}` inside the loop. For nested child rows, use the relationship names from the query and keep each loop balanced. Do not wrap a whole `` with loop tags outside the row. ## Optional clause with a fallback Use the field conditional when a section should disappear for blank or false values. Use a translated Custom Label for reusable wording that administrators maintain in Salesforce. ```html

{#Special_Terms__c}Special terms: {Special_Terms__c}{:else}Standard terms apply.{/Special_Terms__c}

{!$Label.Payment_Terms}

``` The label uses the running user's Salesforce language. The field used by the conditional and its value must be in the template's selected data. ## Reusable terms and approved fonts Save a reusable section under **Portwood → Assets → Terms & snippets**, then insert the copied tag where it should appear: ```html
{%snippet:terms-and-conditions}
``` The snippet itself can contain fields. Save `

Prepared for {Name}.

` in **HTML source**. Include **Name** in your Account template, then insert the copied snippet tag. For an Account named Alder Works, the PDF reads **Prepared for Alder Works.** Inside a Contacts loop, the same field reads the current Contact’s name when **Contacts → Name** is selected. [Follow the snippet exercise](../../UserGuide.md#shared-content) Use the stable API name of an approved custom font. Copy the exact tag from the Custom Fonts area; do not guess a font key or revision: ```html

Prepared for {Account.Name}

``` Snippets are body fragments, not complete HTML documents. Add page-wide CSS in the parent template. Test office output separately; recipients may need the font installed in their Office application. ## QR code and barcode Portwood generates these images natively. Use a short, scannable value for printed QR codes. ```html
Order: {OrderNumber} {*TrackingUrl:qr:150}
{*ProductCode:code128:300x80}
``` Only the supported `qr` and `code128` types render. QR values up to 600 characters are accepted; short URLs and tokens under 120 characters scan more reliably at print size. ## HTML-safe chart patterns For HTML-to-PDF, choose chart styles that render as CSS bars or a table. Inline SVG chart output is suitable for browser HTML but disappears in the Flying Saucer PDF renderer. ```html

Responses by answer

{Chart:Survey_Responses__r:Selected_Answer__c}

Department cross-tab

{Chart:Survey_Responses__r:Selected_Answer__c:pivot:groupBy=Department__c&colSort=Sales,Service&title=Responses by department} ``` Where an entry point supplies a prepared chart PNG, HTML-to-PDF can also display pie, donut, column, line or area charts. Without that PNG the HTML expander supports bar, pivot, clustered and stacked for PDF. Pivot, clustered and stacked require a second selected field in `groupBy=` and a list of column values in `colSort=`. Replace Sales and Service with values from your own records. See the [chart reference](merge-tags.md) and the included survey examples before composing modifiers. ## Signature lines Paste this table directly into the HTML template and assign the signer the **Customer** role when creating the request. You can put a shared clause immediately above the table with its snippet tag. Portwood discovers the signing fields in the main template before it expands the clause. [Example with shared wording](../../UserGuide.md#shared-content) ```html
{@Signature_Customer:1:Full} {@Signature_Customer:1:Date}
``` Use the Signature Sender to prepare uploaded PDFs that do not contain Portwood signature tags. Do not invent signature-role names; match the template's signer setup. ## Page footer Set the template's header or footer HTML and place page counters there. They are not general-purpose body tags. ```html
{Account.Name} · Page {PageNumber} of {TotalPages}
``` ## Large related lists When the child query exceeds the giant-query threshold, keep the outer shell limited to supported parent-level tags and put the long list in the giant-query table. Do not rely on nested child loops, conditions, barcode tags, form fields, or signature tags in the outer shell. For large table rendering, review [repeat table headers](../knowledgebase/articles/repeat-table-headers.md) and [engine tuning](../knowledgebase/articles/engine-tuning.md). ## Adapt a finished design The [design studio](../knowledgebase/articles/document-studio.md) includes complete HTML, JSON, generated PDFs and text editions. Use the [quote](../knowledgebase/articles/cpq-quote.md) for two levels of pricing, the [contents and watermark](../knowledgebase/articles/print-navigation.md) for long proposals, the [renewal brief](../knowledgebase/articles/renewal-decision.md) for missing-data decisions, and the [field work order](../knowledgebase/articles/service-sheet.md) for offline labels. The [event-driven signing example](../knowledgebase/articles/event-signing-journey.md) shows how a Screen Flow opens the signer’s page and checks for the finished File. # Build the event subscriber for a signing workflow For a signed-in employee or portal member signing an agreement, arrange a Portwood site license. Public signing links run under the signing site’s licensed guest user. [Choose signing licenses](https://portwood.dev/guide#user-licenses) Use a business event to start an agreement, then let the rest of the process continue when the signed file exists. A platform-event-triggered Flow runs in its own transaction and has no screen. Keep the customer's navigation in the [Screen Flow handoff](../../UserGuide.md#signing-site-handoff). #### Start a request from an approval event 1. In your own org, define **Agreement Approved** (`Agreement_Approved__e`) with **Publish After Commit** and Text fields `Approval_Key__c` and `Opportunity_Id__c`. These are example names for metadata you create. Publish the event from the approval transaction after recording who approved which agreement version. 2. Create a **Platform Event–Triggered Flow** on that event. Read `$Record.Approval_Key__c` and `$Record.Opportunity_Id__c`. Get the approved Opportunity, confirm its approved version still matches the key, and resolve the intended signer from the approved record. The subscriber needs document, signer and business-record access in its running context. 3. To keep a replay from sending another invitation, create a tracking record with a **unique** approval-key field. Use a value identifying the approval and document version. An ordinary Get-then-Create check allows two simultaneous subscribers through. On a duplicate-key fault, load the existing row. Reuse its request ID, or route an unfinished attempt for reconciliation. 4. Call **Portwood: Create Signature Request** once for the claimed work. Pass the template API name, related record and signer collection. Store the returned request ID and email status on the tracking record. Route both unsuccessful results and faults to a recoverable state. On retry, check for an existing request before creating another. 5. Use Portwood's branded invitation for an unattended send, or start a separate, authorized interactive workflow for the signer. Keep signer URLs out of event payloads. An event subscriber cannot navigate a browser. [Salesforce platform-event Flow behavior](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-subscribe-flow.html) #### Follow activity from the Portwood signing site On the package paths that publish it, **Portwood Signature PDF** (`portwoodglobal__DocGen_Signature_PDF__e`) is an after-commit signal used by Portwood's own subscriber. To inspect those signals, create a second **Platform Event–Triggered Flow**, select this existing event, and use the fields below. Subscribe to events produced by signing. Publishing this internal event yourself can invoke package PDF and notification work. | Event field in a subscriber org | What to do with it | | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$Record.portwoodglobal__Request_Id__c` | Get the Portwood Signature Request by ID. Use its current status and related record. | | `$Record.portwoodglobal__Signer_Id__c` | When populated, get that signer and verify its request matches. In parallel signing this identifies the actor even if people signed out of order. An empty value supports request-level processing only. | A notification can arrive between signers, on a decline, or before final file generation finishes. The package also has paths that complete the PDF without this event. For a business milestone that must cover every signing path, use an after-save record-triggered Flow on **Portwood Signature Request**. Check for **Signed** and a populated **Protected Signed Content Document Id** when the subsequent action needs the final File. Run when the record first meets both conditions. Read the File with the appropriate access. Use the request ID as a unique completion key when delivering to another system. #### Prove the two boundaries In a sandbox, publish the same fictional approval twice. Expect one tracking record and one request. Sign the second invitation first on a parallel two-person test, then decline or complete the other in separate tests. Check that the first signature never starts fulfillment, a decline takes the stopped path, and the completed case links the signed File once. For an uploaded PDF, also exercise finalization without relying on receipt of the package event. # HTML and Word layout reference This advanced reference accompanies the [task-based knowledgebase](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/UserGuide.md). The renderer observations below retain their original probe and release context; the prompt and examples now include 3.62–3.64 capabilities such as Custom Labels, reusable snippets, portable font tags, and optional number decimals. Use the task articles for installation and user workflows. For copy-ready patterns, see [Portwood HTML template recipes](html-recipes.md). #### 5.7.3 CSS rules — what works, what doesn't, and an LLM prompt PDF rendering goes through Salesforce's `Blob.toPdf()`, which is a Flying Saucer engine under the hood. **Flying Saucer is essentially a CSS 2.1 renderer with a small CSS 3 subset.** Modern layout primitives are silently ignored — the page still renders, but your layout collapses to default block flow. The result is a PDF that "looks wrong" without any error message. This section gives you the rules and a paste-ready prompt for ChatGPT / Claude / Gemini so you can have an LLM produce templates that render correctly the first time. ##### Quick reference | Use | Don't use | Replacement | | ---------------------------------------- | -------------------------------------------------- | ----------------------------------------------------- | | `` for side-by-side layout | `display: flex`, `display: grid` | One `
` with one ``, columns become `
`s | | Solid `background-color` | `linear-gradient(...)`, `radial-gradient(...)` | Pick the dominant color, drop the gradient | | `padding`, `margin` | `gap` (CSS 3 grid/flex gap) | `padding` on cells, `margin` on blocks | | Fixed `width`/`height` in `pt`/`in`/`px` | `calc(...)`, CSS variables (`--foo`, `var(--foo)`) | Compute the literal value in your template | | `font-size` in `pt` | `rem`, `em` based on a non-default root | Pt is most predictable for print | | `border` — incl. `dashed` and `dotted` | `border-radius`, `box-shadow`, `text-shadow` | Corners stay square; see "Rounded corners" below | | Hex colours (`#eaf2fb`) | `rgba(...)`, `hsla(...)` | Pre-compute the tint as a flat hex | | Full-strength colour | `opacity` | Pick a lighter hex instead | | `:nth-child(even)` for zebra striping | `:has(...)`, `:is(...)`, container queries | nth-child + nth-of-type are supported | | ``-based two/three-column layouts | `column-count`, `columns` | Tables work everywhere | | `text-align`, `vertical-align` on `
` | `place-items`, `align-self` | Old-school alignment on cells | ##### Rounded corners, shadows and tints — the honest answer **There are no rounded corners.** `border-radius` is ignored in _every_ form: on a `
`, on a `
`, on a `` with `border-collapse: separate`, in the four-value corner shorthand, and via the engine's own `-fs-border-radius`. Boxes render square. This is measured, not inferred — `scripts/css-capability-probe.apex` renders a labelled swatch per property and compares each against a control, and the rendered proof is in `docs/css-capability-probe.png`. An earlier version of this table listed "`border-radius` (basic)" as supported. It is not, and a template built on that advice renders square with no warning. What you can use for visual interest, all CSS 2.1 and all confirmed working: - **`border: 2pt dashed #2b6cb0`** and **`border: 2pt dotted #b02b2b`** — these genuinely render. They are the only border decoration available. - Solid fills, contrasting borders, and `:nth-child(even)` zebra striping. - A background **image** if you truly need a rounded shape — draw it once and reference it; the engine will place it faithfully. Two failure modes that look similar and are not: - **`linear-gradient(...)` is discarded when the stylesheet is parsed.** The cascade then falls back to any solid `background` set earlier, so the element keeps a sensible colour. Harmless. - **`rgba(...)` is not.** It parses, resolves to nothing, and the background disappears entirely — so a tinted panel renders **invisible** rather than falling back to a colour. This is the one that quietly ruins a layout. Compute the tint yourself and write it as a flat hex. `opacity`, `box-shadow`, `transform`, `calc()` and `outline` are all ignored too. ##### Long values overflow a table cell — and no CSS fixes it A value with no spaces in it (an external id, a URL, a base64 fragment, a long product code) will **run straight through the cell border**. This is not a styling mistake; the engine cannot break an unbroken run of characters at all. Measured across every candidate: | Technique | Result | | --------------------------- | ------------------------------------------------------------------------ | | `word-wrap: break-word` | **ignored** — the engine injects this on every cell and it does nothing | | `overflow-wrap: break-word` | **ignored** | | `word-break: break-all` | **ignored** | | `table-layout: fixed` | the column stops growing, so the text overflows the border instead | | `​` zero-width space | **ignored** | | `­` soft hyphen | breaks, but prints VISIBLE hyphens into the value — it corrupts the data | | **``** | **works** — breaks cleanly, and the text is unchanged | So the only correct fix is a `` at each allowed break point: ```html ``` For merged values you cannot pre-break by hand, keep the column wide enough for the longest value you expect, or split the value into its own row beneath the label rather than beside it. Do **not** reach for `­` — a hyphen that was never in the data is worse than a column that is too narrow. ##### How to draw a circle (bullets, status dots, timeline markers) Since `border-radius` does nothing, a circle has to be a **character**, not a box. Unicode circle glyphs render correctly and scale with `font-size`, so you can size one anywhere from a bullet to a display graphic: | Want | Use | Character | | ----------------- | ----------------------------- | --------- | | Small filled dot | `•` (U+2022 bullet) | • | | Filled circle | `●` (U+25CF) | ● | | Hollow circle | `○` (U+25CB) | ○ | | Large hollow ring | `◯` (U+25EF) | ◯ | | Small hollow ring | `°` (U+00B0 degree sign) | ° | ```html ● Delivered • ``` Colour comes from `color`, size from `font-size`, and a light glyph on a dark filled table cell reverses cleanly (white `•` on a solid background). **Never use ZapfDingbats or Symbol for this.** Those fonts are not present in the rendering engine, so `font-family: ZapfDingbats` with the letter `l` or `m` — the usual trick for a filled/hollow circle — falls back to a serif face and prints a literal **"l"** or **"m"** into the document. That is worse than an unsupported property, because nothing fails: a wrong character is silently typeset where a circle was intended. Stick to the Unicode glyphs above, which need no particular font. ##### Paste-ready LLM prompt Copy this verbatim into ChatGPT, Claude, or Gemini. Replace the bracketed sections with what you want. The prompt explains current tag families, but you still need to provide the real object/field API names and check the result in a generated PDF: ``` Generate a single self-contained HTML file for Portwood. Audience: rendered to PDF by Flying Saucer (CSS 2.1 + small CSS 3 subset). Modern CSS layout features are silently ignored. HARD RULES — never use these (Flying Saucer drops them): - display: flex, display: grid, gap - linear-gradient(...), radial-gradient(...), conic-gradient(...) - calc(...), CSS variables (--name, var(--name)) - transform, transition, animation, @keyframes - box-shadow, text-shadow, outline - border-radius — in EVERY form, including on a
{External_Reference__c} ORD-2026-000148-REV3-APPROVED , on a with border-collapse: separate, and the -fs-border-radius variant. There are no rounded corners. Every box is square. Do not attempt a workaround. - rgba(...) and hsla(...) — these do not fall back to a solid colour, the background disappears completely. Write a pre-computed flat hex instead. POSITIONING — measured 2026-08-05, not assumed. `position: absolute`, `relative`, `fixed` and `float` all WORK and are pixel-exact against declared inches. Two limits that matter more than the support itself: - An absolutely positioned box with **no explicit height GROWS** to fit merged content, background and border following it. Pin a height and the content overflows the box instead — visible, not clipped, but the chrome stays put. - Nothing beyond **page 1** renders. A box at `top: 10.5in` on Letter is dropped entirely. Absolute layout is single-page; use one artboard per page. - opacity — pick a lighter hex colour instead. - :has(), :is(), :where(), container queries USE INSTEAD: -
for any side-by-side layout. One , columns are ``` The sample uses the same printed width for every track. Test 0, 50 and 100 before adding more teams. If your metric can exceed 100%, decide how you want to label it and bound the display width in the data. #### Adapt the story Try the supplied **72%**, then change the data to **84%**, `AtTarget` to true and the team counts to match. Finally set `HasUsage` to false. Generate all three files. The headline, metric band and chart should agree. The same pattern works for a project health report, a grant milestone or an account statement. [Run the example](#document-studio) ## Print a scannable field-service work order A technician needs to find the right machine, see the checks for that unit and bring a short receipt back to the office. This printable work order gives each asset a QR code, a readable identifier, a checklist and room for the as-found reading. [Open the service sheet](https://portwood.dev/demos/studio/service-sheet.pdf) · [Read the text edition](https://portwood.dev/demos/studio/service-sheet-reading.html) · [Download the design files](https://portwood.dev/demos/studio/document-studio.zip) [View HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/service-sheet.html) · [View data](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/service-sheet.json) ![Printable work order with two separate equipment cards, scannable asset codes and a detachable desk receipt](docs/images/userguide/v3.64/work-order.png) #### Put the identifier in two places Inside the `Equipment` loop, the sample prints `{*Code:qr:105}` and the plain value `{Code}` below it. The first code decodes to **AW-P17-201** for the circulation pump. The second is **AW-S08-414** for the flow sensor. Someone with a damaged label can type the printed value. These codes carry text and work offline. To open an asset page, supply an authorized HTTPS destination as the code value and test it as the intended user. [QR codes, images and barcodes](#charts-and-codes) #### Keep each machine with its checks The outer `{#Equipment}` block repeats the whole card. Inside the card a smaller `{#Checks}` loop repeats one task at a time. A short card uses `page-break-inside: avoid` so its code, title and checks travel together. If one machine has enough checks to fill a page, allow the checklist to continue and repeat a small identification band on the following sheet. The printed squares and ruled lines are for handwriting. For a form that someone fills electronically, use the [fillable PDF workflow](#fillable-pdf). The lower desk receipt has its own work-order number, so the office can match it to the job after it is detached. #### Check one physical copy Print at actual size on the paper the crew will carry. Scan each code and compare the result with the printed identifier. Leave white space around it, and confirm there is room to write the reading and initials. For a new customer, update the work-order JSON and generate the same HTML again. [Run the sample](#document-studio) ## Design an advanced document with print CSS Build a service schedule that can grow from two rows to several pages and still leave a clean acceptance page. This lab uses Account as the parent and Opportunities as the child relationship. All estimates in the example use a single currency. [Add a working contents page and a conditional draft watermark.](#print-navigation) #### Assemble the example 1. In **Assets → Terms & Snippets**, create an active snippet with the key `guide-service-handoff`. Paste the [handoff fragment](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/handoff-fragment.html) in **HTML source** and save it. 2. Create an Account HTML template. Select Account **Name** and the child **Opportunities** relationship with **Name** and **Amount**. Give the child rows a stable sort order. 3. Upload the [service review HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/service-review.html). Paste the [two-line footer](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/footer.html) into **Footer HTML**. Save a new version. 4. Generate once for a short schedule and again with enough rows to cross a page. Compare the last row on each page with the first row on the next. Use [the rendered sample](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/service-review.pdf) as a visual reference. #### Establish the printable area Letter is 8.5 inches wide. Side margins of 0.65 inches leave 7.2 inches for the table. Reserve space vertically for the footer. Choose one place to control paper and margins. With this example the HTML owns the page setup. ```css @page { size: Letter portrait; margin: 0.7in 0.65in 0.85in; } .ledger { width: 100%; table-layout: fixed; border-collapse: collapse; } .ledger td { padding: 6pt 7pt; vertical-align: top; } ``` A two-cell masthead gives the account team a solid band on every first page. Set the band color on the cells. Use points for text, percentages for column widths, and right alignment for money. Keep the estimate column wide enough for your largest formatted value. #### Keep a long schedule readable ```css .ledger { -fs-table-paginate: paginate; } .ledger thead { display: table-header-group; } .ledger tr { page-break-inside: avoid; } h2 { page-break-after: avoid; } .appendix { page-break-before: always; } ``` Put real headings in a `thead`. Inside the data row, open `{#Opportunities}` in the first cell and close it in the last. Put `{RowNumber}` inside that row and the aggregate outside it. Use `page-break-inside: avoid` on individual rows or a short totals panel. Applying it to the entire table asks the renderer to keep many pages of content together. A single row taller than a page needs a different layout. ![Page two of the generated schedule repeats the column headings and continues the original row numbering.](docs/images/userguide/v3.64/schedule-continuation.png) The appendix starts on a fresh page. Compare a zero-row account with a long schedule. If you want to omit an empty schedule, gate the heading and table together with `{#IF Opportunities.totalSize != 0}` and `{/IF}`. #### Choose how the footer is drawn The main stylesheet supplies `content: counter(page)` and `counter(pages)` on the two footer spans. The footer field supplies the HTML. This keeps a second line of text and its styling together with the counter. For a single line, enter `Page {PageNumber} of {TotalPages}` in Footer HTML. Check the last page after changing a margin or font. [Running headers and footers](#running-headers-footers) #### Extend the design | Design request | Technique to try | Inspect in the PDF | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | | Full-page stationery | Upload page-sized artwork in **Watermark / Background**. Choose **Original** for opaque artwork. Use a 816 × 1056 px image for Letter at 96 DPI. | Artwork reaches the edges while the body stays inside its margins. [Page layout](#page-layout) | | Branded headings | Apply the approved face's copied font tag inside a quoted inline style. Test each weight and script with real text. | Compare the glyphs and line breaks. [Custom fonts](#custom-fonts) | | Side-by-side summary cards | Build one table row with separately colored cells. Use solid hex fills, cell padding and a narrow gutter cell. | Both cards fit at their longest values. | | Rounded badges, a gradient or a seal | Put that artwork in a sized image asset. Keep changing text in adjacent HTML. | Edges stay crisp at actual print size. [Images and assets](#images-and-assets) | | A very long unbroken reference | Insert break opportunities in the source value or give the identifier its own line. | Long strings fit without overwriting the next cell. | | Charts inside a report | Use a prepared chart image on paths that supply one. For portable HTML-to-PDF use a CSS bar or pivot table. | Generate from the intended button, Flow or bulk path. [Chart modifiers](#tag-charts) | The [CSS capability probes, measured comparisons and layout rewrites](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/reference/template-layout.md) cover selectors, transparency, box shadows, image sizing and Word table widths. Use [grouped reports](#grouped-reports) to add one table per service category. #### Build the executive version For a portfolio review, select **StageName** as well as **Name** and **Amount** on the child Opportunities. Upload the [portfolio brief](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/portfolio-brief.html). Its cover combines a two-cell metric band, a chart grouped by stage and a conditional review note. The next page uses `{#GroupBy Opportunities by StageName}` to make one table per stage. The nested Opportunities loop numbers the lines within that group and the sum inside the group prints its subtotal. In the [sandbox-rendered portfolio PDF](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/portfolio-brief.pdf), six engagements total **41,900.00**. The three subtotals are **11,000.00**, **19,900.00** and **11,000.00**. Compare them with the cover total before reusing the layout with your own data. ## Merge Salesforce Files in Flow Combine an approval letter and a schedule already stored in Salesforce Files. This Flow action creates a new File and returns its IDs, so a later step can attach it to a record or offer it to the user. 1. In a sandbox, open the bundled **Portwood: PDF Merge Demo** in Flow Builder. It ships as a draft. Debug it with two small unsigned PDFs you can read. 2. Supply **Content Version IDs** as an ordered Text collection, or **Content Version IDs (Text)** as a single value separated by spaces, commas, semicolons or line breaks. Choose one input. Use exact version IDs beginning with `068`. A document ID beginning with `069` identifies the file across revisions and cannot select the source revision. 3. Set **Document Title**. Set **Related Record ID** to link the new File there. Leave it blank for a standalone File. 4. Turn on **Pad Odd Documents** for duplex printing. Every odd-length source gets a trailing blank, including the last source. Repeating an ID repeats that PDF. 5. Branch on **Success**. Keep **Content Version ID** for that output revision and **Content Document ID** to open or link the File. Display **Error Message** on failure and connect a fault path. ![In the PDF Merge Demo, enter a name for the new File and select Add blank pages for double-sided printing.](docs/images/userguide/v3.64/merge-duplex.png) One one-page letter followed by one two-page schedule produces three pages normally, or four with padding. Flip through the result and verify the first page of the schedule comes after the blank. The action accepts 2–100 source versions and checks their combined input size before reading them. The budget is at most 384 KiB synchronously and 768 KiB asynchronously. Available Apex heap can lower it. Each repeated input counts again. Encrypted or signed PDFs, XFA, and scripted/calculation forms are rejected. For a signed agreement, assemble its final contents before requesting signatures. For an interactive desktop download, see [Document packets](#document-packets). The [sandbox-generated duplex packet](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/duplex-packet.pdf) uses two one-page sources. The welcome letter is on page 1, the flattened acceptance form is on page 3, and pages 2 and 4 are blank. If the input box in the bundled demo shows only a comma, its two sample Files are missing or unavailable to you. You can have your own Flow look up each **Content Version** with **Get Records**. Match **Content Document ID** to the File you selected and **Is Latest** to **True**, then use that version’s **Id** in your ordered list. For a familiar first run, use the downloaded sample letter and acceptance form from the [recipe library](#recipe-library). Upload the two PDFs to Files and use their version IDs in the sample Flow. ## Open the signing site from a Screen Flow Give a signed-in person a button that opens their own Portwood signing page. They can return to the same Flow to check the signed file. This walkthrough uses the [background Flow that prepares the agreement](#signing-events). [See the screens as a signer](#event-signing-journey) For a members-only portal or employee signing experience, authenticated signing requires a **Portwood site license**. If the button opens a public signing page, configure that site’s guest user as well. [Plan signing access and request a quote](#user-licenses) #### 1. Put a Prepare agreement button on the screen In **Setup → Flows → New Flow**, select **Screen Flow**. Under **Start**, select **+ → Screen**. Drag **Display Text** onto it and enter a short explanation of the agreement. In the screen’s footer settings, give the **Next** button the label **Prepare agreement**. Below that screen, add **Create Records**. Choose **Manually** for setting field values and select the **Guide Sign Requested** object. Add **Receipt key** and choose **Running Flow Interview → InterviewGuid** as its value. This identifies this interview if the person checks back several times. ![Create Records publishes Guide Sign Requested with Receipt key set to the running Flow’s InterviewGuid.](docs/images/userguide/v3.64/publish-event.png) Add a second **Screen** immediately after it. Enter **The request is being prepared** and label its Next button **Open signing page**. Reaching this screen commits the platform event so the background Flow can start. Label the Flow and save a draft. In **Auto-Layout**, your first few steps should read from top to bottom like this. ![The screen, the event and the second screen are separate steps before Read my receipt.](docs/images/userguide/v3.64/screen-path.png) #### 2. Find the right person’s link After the second screen add **Get Records** on **Guide Signing Receipt**. Set **Condition Requirements** to **All Conditions Are Met (AND)**. Match **Receipt key** to **Running Flow Interview → InterviewGuid** and **Owner ID** to **Running User → Id**. Store the first matching record. In the pictured example this element is labeled **Read my receipt**. ![Get Records looks for both the interview’s receipt key and the signed-in user’s owner ID.](docs/images/userguide/v3.64/read-receipt.png) Add a **Decision**. A receipt is ready when **Preparation status = Ready**, its **Private signing URL** has a value and **Handoff link expires** is in the future. For an empty result or a receipt still preparing, show a **Check again** screen and connect it back to **Get Records**. For a failed or expired receipt, show a message and a contact for help. #### 3. Open the signing site with Salesforce’s standard action On the ready branch select **+**. In **Search Elements** type **Open a Page** and choose the navigation action. You can also open the **Action** picker and search there. ![Searching the plus menu for Open a Page brings up the navigation action.](docs/images/userguide/v3.64/find-navigation.png) Give it the label **Open the signing page**. In **Page Type**, select **External Web Page**. For **URL**, use the resource picker to select **Guide Signing Receipt from Read my receipt → Private signing URL**. For **Where to Open the Page**, select **New Browser Tab**. Salesforce provides this action in Flow API 67 and later. [Salesforce Open a Page action](https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_open_a_page.htm&language=en_US&type=5) ![The three navigation settings show External Web Page, the receipt’s private signing URL, and New Browser Tab.](docs/images/userguide/v3.64/open-signing-page.png) If the URL picker says the field is unavailable, check the **Read** permission on **Private signing URL** for the person using Flow Builder, reopen the Flow and reselect the field. If this Screen Flow creates the request directly, pass its single **Signer URLs** item as the URL. Scope the link to the intended signer. For an internal coordinator who needs the staff view, choose **Salesforce Record Page**, the saved signature request ID, the Portwood Signature Request object and **View**. Signing takes place at the person’s private web link. #### 4. Let the person return and check the file After the action add a **Screen** with **Display Text**. Type **review and sign your agreement**, select those words, and use the link control to insert the same signer URL resource. Connect the action’s fault path to this screen as well. A person whose browser blocks the new tab can still choose the link. Set the Next button label to **Check signing status**. Then **Get Records** on **Portwood Signature Request** using the saved **Signature request ID**. On a **Decision**, show success when **Status = Signed** and **Protected Signed Content Document Id** is populated. Give **Signed** requests that are still saving their file a separate screen with **Check again**. For a declined or cancelled request, or one past its signing expiry, show a stopped screen. Send an unreadable request to your help screen. On the **still needs a signature** screen, add a **Checkbox** labeled **Reopen my signing page** and a **Check again** footer button. Add a Decision after that screen. When the box is checked, connect it back to **Read my receipt** so the Flow checks this person’s ownership, link and expiry before opening the same agreement. Otherwise connect it to the request-status lookup. Both paths reuse the initial request. #### 5. Give your team a place to open the Flow 1. In **Flow Builder**, save the Screen Flow with a recognizable label such as **Guide · Request and open an agreement**. Activate the cleanup and background Flows first, then activate the Screen Flow. An active Screen Flow appears in the Lightning page’s Flow picker. 2. For a dedicated page, open **Setup → Lightning App Builder → New → App Page**. Select **Next**, label the page **Service agreements**, choose **Next → One Region → Done**. To use an existing record page instead, open a record and choose the gear menu’s **Edit Page**. 3. Under **Components**, search for **Flow**. Drag the standard **Flow** component into the page region. Select it on the canvas and use the **Flow** dropdown in the properties panel to pick your Screen Flow. ![In Lightning App Builder, the Components pane is on the left, the Flow sits on the page in the middle, and its settings are on the right.](docs/images/userguide/v3.64/host-palette.png) ![The Flow dropdown has Guide · Request and open an agreement selected.](docs/images/userguide/v3.64/host-selected.png) 4. Select **Save → Activate**, or **Activation** on an already-saved page. For an app page, choose which users can see its tab and add it to your team’s Lightning app under **Lightning Experience**. For a record page, select the app, record type and profile assignment your signers use. [Salesforce app page activation](https://help.salesforce.com/s/articleView?id=platform.lightning_page_getting_into_salesforce1.htm&language=en_US&type=5) 5. As a practice signer, open the assigned app, select **Service agreements**, and choose **Prepare agreement**. If you used a record page, open that record in the assigned app. Open the signing page, close that tab before signing, then check the status and try **Reopen my signing page**. You should get the same agreement. [See the signer’s screens](#event-signing-journey) If everyone should stay on the same page throughout, [place the signing component inside the Flow](#flow-signatures). Admins can also [download the optional working project](https://portwood.dev/demos/studio/event-signing.zip). ## Set up a signing receipt and event To let someone wait for a signing link in a Salesforce screen, give the screen and the background Flow a private place to meet. In this example a **Guide Signing Receipt** remembers which request belongs to the person. A **Guide Sign Requested** event tells the background Flow to start preparing it. Set these up once in a sandbox. This example starts with a signed-in person. For a portal or employee signing rollout, arrange a **Portwood site license**. It also covers the guest user if the Flow opens a public signing page. [Check signing licenses and request a quote](#user-licenses) #### 1. Make the receipt in Object Manager 1. Open **Setup → Object Manager → Create → Custom Object**. Enter **Guide Signing Receipt** for the label and **Guide Signing Receipts** for the plural. Use `Guide_Sign_Receipt` for **Object Name** to match this example. For the record name, use **Receipt number**, choose **Auto Number** and enter `HANDOFF-{00000}` as the display format. Save. 2. In **Fields & Relationships**, select **New** for each row below. Use these field names if you want to match the pictured example. Salesforce adds the `__c` suffix. | Field label | Field name | Type and setting | | -------------------- | ----------------- | ---------------------------------------------------------------------------------------- | | Receipt key | `Receipt_Key` | Text, 100 characters. Select **Unique** and treat uppercase and lowercase as duplicates. | | Preparation status | `Stage` | Text, 24 characters. The Flow uses **Preparing**, **Ready** and **Failed**. | | Signature request ID | `Request_Id` | Text, 18 characters. Holds the Portwood request ID. | | Private signing URL | `Signer_URL` | Long Text Area, 4,096 characters. Holds this signer’s personal link temporarily. | | Handoff link expires | `Link_Expires_At` | Date/Time. The screen checks this before opening the link. | ![In Object Manager, the receipt fields include the private signing URL and a unique receipt key.](docs/images/userguide/v3.64/receipt-setup.png) 3. In **Setup → Sharing Settings**, set the receipt object’s default access to **Private**. In a permission set, give participants **Read** on the receipt and the fields above. The background Flow creates and updates receipts. Restrict access to the signing URL when you review role hierarchy, sharing rules and administrative access. Open **Manage Assignments → Add Assignment** on the permission set and assign it to the people who run this screen. Give the person **Run Flows** and access to the screen Flow if your org restricts individual Flows. #### 2. Create the platform event 1. In Setup’s **Quick Find**, enter **Platform Events**. Open it and select **New Platform Event**. Set the label to **Guide Sign Requested** and use `Guide_Sign_Requested` for the object name. 2. Set **Publish Behavior** to **Publish After Commit** and save. Under **Custom Fields & Relationships**, choose **New → Text**. Use **Receipt key**, field name `Receipt_Key`, length **100**. The event carries only this key. ![The platform event definition shows Guide Sign Requested and Publish After Commit.](docs/images/userguide/v3.64/event-definition.png) 3. In the participant’s permission set, grant **Read** and **Create** on this event, and **Read** and **Edit** on its **Receipt key** field. Give the Flow’s execution user access to the records, template and Portwood action it uses. Test as a person who will actually sign. #### 3. Give Portwood an agreement to prepare In **Portwood → My Templates → New Template**, choose **Bring an Existing Template**, **Salesforce Record (SOQL)** and **HTML**. Select **Guide Signing Receipt** as the base object and add **Name** to the selected fields. Set **API Name** to `Guide_Event_Acceptance` and **Output Format** to **PDF**. Select **Next → Create Template**. Under **Upload New Version**, select **Choose File** and upload the [practice agreement HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/event-signing/acceptance.html), or use your own HTML agreement. Select **Save as New Version** and confirm the template is active. Put the **Customer** signature field directly in the main template body. Confirm your org’s signing site works with a practice request. [Prepare a signable template](#sign-template) · [Set up external signing](#setup-signatures) Now [build the background Flow that prepares an agreement](#signing-events). If your team already has an approval event and a private tracking record, map their fields to the same roles when you follow that walkthrough. ## Prepare a signature request when a platform event arrives Build the background half of a signing experience. When someone chooses **Prepare agreement** on the screen, this Flow creates one Portwood request and puts their personal signing link on their private receipt. Start with the [receipt, event and signable template](#signing-handoff-setup). #### 1. Start a Flow when the request arrives In **Setup → Flows**, select **New Flow**. In **New Automation**, choose **Platform Event—Triggered Flow**. In **Choose Platform Event**, search for and select **Guide Sign Requested**. If you return to the canvas, select **Start → Edit** to see the chosen event. ![Choose Platform Event—Triggered Flow for the background work. Screen Flow is the separate choice for the person’s interview.](docs/images/userguide/v3.64/flow-type-choice.png) ![Choose Platform Event is set to Guide Sign Requested.](docs/images/userguide/v3.64/trigger-event.png) Under **Start**, select **+ → Get Records**. Find the first **Guide Signing Receipt** where **Receipt key** equals **Triggering Guide Sign Requested → Receipt key**. Add a **Decision**. When a receipt already exists, end that path. On the other path, use **Create Records** to create a receipt with the event’s key, **Preparation status = Preparing** and **Owner ID = the event’s Created By ID**. Keep the new record’s ID. The unique key also prevents two simultaneous deliveries from creating two receipts. #### 2. Tell Portwood who is signing Use **Get Records** to find the **User** whose **Id** equals the event’s **Created By ID**. In **Manager → New Resource → Variable**, create a variable named `Person`, choose **Apex-Defined**, and select the packaged **DocGenSigner** class. Create a second variable named `People` with the same type and select **Allow multiple values (collection)**. Add an **Assignment**. Set `Person.name` to the User’s **Full Name**, `Person.email` to the User’s **Email**, and `Person.role` to **Customer**, matching the template. In the last row select `People`, change the operator to **Add**, and select `Person`. ![The Assignment sets the signer’s name, email and Customer role, then adds Person to the People collection.](docs/images/userguide/v3.64/assign-signer.png) #### 3. Create the signature request Select **+** and search for **Create Signature Request**. Choose the Portwood action. For **Related Record Id**, select the receipt you just created. Enter these inputs for a person who will open the site from the same interview. | In the action | Choose this value | | ---------------------- | ----------------------------------------------------------------------------------------------- | | Signers | `People` | | Signing Order | `Single` | | Template API Name | `Guide_Event_Acceptance` | | Send Branded Emails | `False`. The screen supplies the initial invitation. | | Link Expiration (Days) | `1` for this practice agreement. Leave the signer verification policy to your template and org. | ![The signing action uses People, Single, and the API name of the active agreement template.](docs/images/userguide/v3.64/signer-inputs.png) #### 4. Put the result on the receipt Use a **Decision** to check the action’s **Success** output. On success, use a **Loop** over **Signer URLs**. This example has one signer. Inside the loop, assign the current item to a Text variable named `SignerLink`. After the loop, confirm the link is populated. Use **Update Records** on the receipt you just created. Set **Signature request ID** to the action’s **Signature Request Id**, **Private signing URL** to `SignerLink`, **Preparation status** to `Ready`, and **Handoff link expires** to a Date/Time formula containing `NOW() + 1`. On an action fault, unsuccessful result, or missing link, update the receipt to **Failed** and keep any returned request ID for investigation. ![The receipt update saves the expiry, Portwood request ID, private signer link and Ready status.](docs/images/userguide/v3.64/receipt-fields.png) To clear the temporary URL, add a separate record-triggered Flow on the receipt. Run it after save when a receipt first meets **Preparation status = Ready**. Under **Start → Add Scheduled Paths**, use **1 Day After** the record-triggering event. On that path, use **Update Records** to clear **Private signing URL** on the triggering receipt. The practice agreement and the local expiry both use one day. The screen also checks expiry immediately before navigation. Save both Flows. If Salesforce asks for a **Default Workflow User** when you activate the scheduled cleanup, set it in **Setup → Process Automation Settings**. Activate the cleanup and background Flows in your sandbox. Next, [build the screen that opens the signing site](#signing-site-handoff). #### If a manager’s approval starts the process Use the approved agreement and version as the unique key. Find the authorized customer on the approved record. The publishing user in this case is the manager, while the invitation belongs to the customer. For multiple signers, route each person’s own link to them. Test one approval twice and check that it produces one request. In a parallel two-person test, let the second person sign first. Fulfillment should still be waiting. #### Tell the service team when the signed file is ready 1. Create a **Record-Triggered Flow** on **Portwood Signature Request**. In **Start**, select **A record is created or updated** and **Actions and Related Records**. 2. Under **All Conditions Are Met**, set **Status** to **Signed** and **Protected Signed Content Document Id → Is Null** to **False**. For updates, choose **Only when a record is updated to meet the condition requirements**. A signer can finish before the protected File is ready. 3. On that path, create the team’s follow-up task on the related business record, or pass the signed File ID to your delivery step. If another system can retry delivery, use the request ID as its unique reference. Try opening the finished File as someone on the receiving team. For a separate notification each time a person signs, a **Platform Event–Triggered Flow** can listen to **Portwood Signature PDF** where the package emits it. Look up the request and the event’s signer. Use the request’s final status and File for fulfillment across signing methods. [Approval and fulfillment field map](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/reference/signature-event-recipe.md) ## account-letter.html ```html Account letter

Welcome, {Name}

We will use this account name on your service documents.

``` ## service-review.html ```html Service review
s with explicit widths. - Solid background-color as a HEX value (no gradients, no rgba). - padding/margin in pt or in. gap is not a thing. - font-size in pt. Standard fonts: Helvetica, Arial, "Times New Roman", Courier. - text-align / vertical-align on for alignment. - Fixed width/height in pt or in. - For visual interest use solid fills, contrasting borders, and :nth-child(even) zebra striping. border: dashed and border: dotted DO work and are the only border decoration available. - CIRCLES (bullets, status dots, markers) must be CHARACTERS, never CSS boxes, because border-radius does nothing. Use these and size them with font-size, colour them with color: • small filled dot (U+2022) ● filled circle (U+25CF) ○ hollow circle (U+25CB) ◯ large hollow ring (U+25EF) ° small hollow ring (U+00B0) e.g. ● Delivered NEVER use font-family: ZapfDingbats or Symbol to make a circle. Those fonts are absent, so the letter falls back to a serif face and prints a literal "l" or "m" in the document instead of a shape. PAGE SETUP — put a single
Quote #: {Name}
Date: {Today}
Prepared For
{Account.Name}
{Account.ShippingAddress}
Prepared By
{RunningUser.Name}
{RunningUser.Email}
Line Items
{#OpportunityLineItems} {/OpportunityLineItems}
Product Qty Price Total
{Product2.Name} {Quantity} {UnitPrice:currency} {TotalPrice:currency}
Total {Amount:currency}
Customer Signature
{@Signature_Buyer}
Date
{@Signature_Buyer:1:Date}
``` ##### Common conversion patterns When an LLM (or a designer) hands you a template using modern CSS, here are the mechanical rewrites: **Flex header → table header** ```html
Date: {Today}
ACME Date: {Today}
``` **Grid columns → table columns** ```html
Left content
Right content
Left content Right content
``` **Gradient → solid color** ```css /* BEFORE */ .accent-bar { background: linear-gradient(to right, #004693, #35c6f4); } /* AFTER */ .accent-bar { background-color: #35c6f4; } ``` **`gap` between rows → margin** ```css /* BEFORE */ .stack { display: flex; flex-direction: column; gap: 12px; } /* AFTER */ .stack > * { margin-bottom: 12px; } ``` ##### `@page` rules — don't double-declare Two ways to control the page size, margins, and orientation: 1. **Template fields** — `Page_Size__c`, `Page_Orientation__c`, `Page_Margins__c`, `Custom_Margins__c` on the Portwood Template record. Portwood wraps the template's HTML with an engine ``. 2. Put the following HTML in the template's **Footer HTML** field. 3. Keep literal `{PageNumber}` and `{TotalPages}` out of that header/footer. 4. Save a new active version and generate a multi-page PDF. ```css .pw-page-number:before { content: counter(page); } .pw-total-pages:before { content: counter(pages); } ``` ```html
Page of
Northstar Bikes | 317-555-0142 | hello@example.com
``` With this setup, Portwood repeats your formatted footer and CSS supplies the page numbers. Generate a document long enough to cross a page. Keep both footer lines visible and check that `Page 1 of 4` advances all the way to `Page 4 of 4` in a four-page file. #### Make room for it Set enough top/bottom margin for the actual logo, line height, and number of lines. Choose one owner for page size and margins. Imported `@page` rules, the designer's page setup, and header/footer controls can otherwise compete. Keep counters in page furniture. These are PDF layout counters, not record fields or row numbers. A packet assembled from separately rendered PDFs can retain numbering from each original document; test whether that meets your requirement for the final packet. #### When something still looks wrong | Symptom | Check | | ------------------------------------- | -------------------------------------------------------------------------------- | | Everything becomes one line | Remove literal page-number tags from that header/footer and use counter spans | | Footer overlaps the body | Increase the bottom margin and reduce oversized content | | Page number is blank | Keep the CSS in the main body stylesheet; verify exact class names and final PDF | | Custom font and literal counters fail | Use running HTML plus CSS counters and test the approved font specimen | | Header image is missing | Confirm image access and dimensions in the actual render path | This recipe adapts Dave's [two-line footer answer in Portwood Community](https://portwoodcommunity.slack.com/archives/C0B37JT11RA/p1792162191491549). You can compare the layout with the [finished service schedule](#css-print-lab). ## Build grouped reports without broken table markup Use one dataset and `{#GroupBy}` when the categories can change. Use deliberately filtered query aliases when each section has a different data-selection rule. [Build nested bundle tables from a priced quote.](#cpq-quote) #### One table per stage Select Opportunities with `Name`, `StageName`, and `Amount`. Sort by `StageName` if you want groups in stage order. This HTML wraps a complete table in the group and keeps the row loop inside its cells: ```html
{#GroupBy Opportunities by StageName}

{GroupName}

Opportunity Amount
{#Opportunities}{Name} {Amount:currency}{/Opportunities}

Stage total: {SUM:Opportunities.Amount:currency}

{/GroupBy}

All stages: {SUM:Opportunities.Amount:currency}

``` Inside the group, the Opportunities relationship contains that group's members. Outside it, the total sees the whole available relationship. `{RowNumber}` restarts within each group's row loop. #### A different alias is not a filter Renaming `{#QuoteLineItems}` to `{#Purchase}` does not select purchase items. `Purchase` must exist in Query Config or the supplied data. Either configure two filtered aliases, use a prepared provider, or keep the real relationship and apply conditions to its rows. A conditional display does not automatically change an aggregate over the unfiltered relationship. #### Keep table HTML valid Do not place naked loop/IF text directly between ``, ``, and ``. Browsers can move that text outside the table before Portwood processes it. Keep row-loop markers in cells, and place group markers outside complete tables. After switching between visual editing and HTML, inspect the saved markup and preview again. #### Respect scope Within a Contact loop, `{Name}` means the Contact's Name. To print the root Account's Name, use a uniquely named root block such as `{~AccountHeading}{Name}{/AccountHeading}`. Root-scope blocks are unsupported inside giant-query loops; use a prepared layout/data structure for that case. Test zero, one, and several groups, blank category values, and long labels. Compare group totals with a trusted Salesforce report before sharing the document. ## Tune a demanding document Start with the smallest document that proves the business result. Add data, graphics, and styling in stages so you can tell which change creates a problem. #### Pick the path for the job | Job | Starting point | | ---------------------------------------------------- | ------------------------------------------------------------ | | One normal record, interactive download | Record-page Runner | | Many parent records | Bulk Generation or Generate Bulk Documents Flow action | | One parent with a very large child list | Auto Giant Query / the supported giant-query path | | Computed or external data already prepared | JSON data or `DocGenDataProvider`; own the access checks | | A PDF Blob for another process, without a saved File | Global `DocGenService.generatePdfBlob…` | | A packet of Portwood-native PDF parts in Apex | Global `DocGenPdfMerger`, within its supported PDF structure | Giant-query generation is asynchronous once it crosses the engine's large-relationship threshold. Follow the returned job rather than expecting an immediate File Id. It is different from bulk generation across many parent records. #### Make the data smaller before making the heap larger Select only used fields, filter relationships, order them deliberately, and set justified limits. Avoid huge rich-text fields and full-resolution images when the document prints a small thumbnail. A query limit changes the document's data and totals; disclose intended truncation to the reader rather than quietly hiding rows. Use standard retrieval when it fits. When you supply JSON or an Apex map, Portwood cannot know whether your code was allowed to retrieve each value; enforce sharing, object access, and field access in the caller/provider. #### Work with transaction boundaries Do not assume a rendering API can run synchronously from a trigger or after arbitrary DML. Queue the document work into a fresh transaction and test the exact Flow/Apex entry point. Bulk rendering, chart preparation, file saves, and merging all consume resources. A method accepting a list does not promise unlimited work in one transaction. Keep durable job outcomes and retries in your own process. Avoid retrying after an uncertain success without checking for the existing File/request; duplicate retries can create duplicate documents or invitations. #### Use the PDF engine's strengths Use tables for aligned print layouts, fixed units for controlled dimensions, simple borders, and a supported font. The renderer follows a CSS 2.1/paged model; browser flex/grid layouts, shadows, rounded corners, and JavaScript are not a reliable PDF design foundation. Use a pre-rendered image when a visual effect cannot be represented by the print engine. For precise Word conversion, fix table widths and AutoFit rather than repeatedly changing the PDF's margins. The [layout reference](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/reference/template-layout.md) includes the width traps and a constrained HTML-authoring prompt. #### Diagnose one variable at a time 1. Confirm the template, active version, record, output type, and running user. 2. Reduce to one field and one related row. 3. Add the original query selection, then loops and totals. 4. Add images, then charts, then page furniture. 5. Reintroduce the failing data volume last. 6. Compare preview, record Runner, and the actual automation path; they can prepare assets differently. For a release, keep small, empty, long-text, many-row, multi-page, and representative image cases. Inspect the final files, not only the designer preview. A screenshot captures a symptom; the template version, query, data shape, and execution path make it reproducible. ## Generate documents from your own Apex Use `portwoodglobal.DocGenService` from subscriber Apex. Start with the method that matches the result your process needs. #### Choose the method | Result you need | Global method | Result | | ----------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------- | | A File on the source record | `generateDocument(templateId, recordId)` | `ContentDocumentId` | | An explicit compatible output type | `generateDocument(templateId, recordId, outputFormatOverride)` | `ContentDocumentId` | | A saved File with a chosen title | `generateDocument(templateId, recordId, outputFormatOverride, documentTitle)` | `ContentDocumentId` | | A different attachment target | Add `attachmentRecordId` as the fifth argument | `ContentDocumentId`; null target creates a standalone File | | PDF bytes without a saved File | `generatePdfBlob(templateId, recordId)` | Map with `blob` and `title` | | A saved File from an already prepared map | `generateDocumentFromData(templateId, recordId, data)` | `ContentDocumentId` | | PDF bytes from a prepared map | `generatePdfBlobFromData(templateId, data)` | Map with `blob` and `title` | | Prepared data with record context | `generatePdfBlobFromData(templateId, recordId, data)` | Map with `blob` and `title` | | Prepared data, output type, and File save | `generateAndSaveFromData(templateId, recordId, data, outputFormatOverride)` | `ContentDocumentId` | `generateAndSaveFromData` also accepts a fifth `documentTitle` and a sixth `fileAttachmentTarget`. The second argument remains required. Passing a null sixth argument creates a standalone File; use a Blob method if you want no File at all. #### Generate after the business transaction A trigger or Flow can change records and then queue the document work. The worker gets a fresh transaction. Rendering is subject to platform transaction rules; do not paste a synchronous PDF call directly into a trigger and assume it is supported there. The downloadable [KBGenerateAccountBrief class](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/apex/KBGenerateAccountBrief.cls) was deployed and executed in the fresh subscriber org. It looks up the template by its stable API Name and calls the global generation service from a Queueable implementing `Database.AllowsCallouts`. ```apex // Run in your process after deciding this Account needs a document. System.enqueueJob(new KBGenerateAccountBrief(accountId)); ``` The example uses `KB_Account_Brief`, the [worked example](#example-library). Replace that stable key with your own template API Name. For a real deployment, add job outcome reporting, retries with duplicate protection, access checks appropriate to the caller, and tests for the business trigger. #### Return bytes to another process ```apex Map result = portwoodglobal.DocGenService.generatePdfBlob(templateId, accountId); Blob pdf = (Blob) result.get('blob'); String title = (String) result.get('title'); // Your code can attach the bytes to an email or pass them to another system. // This Portwood method does not itself send an email or create a File. ``` Read all inputs before rendering; keep preceding DML out of the render transaction. Test the exact document, image, and chart path you will use. Large outputs still consume Apex heap even when you do not save a File. #### Handle access and failures deliberately The standard retrieval path uses user-mode queries. A prepared map skips the source-record retrieval; template, file, font, and other supporting queries can still consume SOQL budget. Prepared maps and custom providers bypass that retrieval, so caller code must enforce access on the data it supplies. `with sharing` alone does not enforce field access. Catch `portwoodglobal.DocGenException` for Portwood validation failures, and handle other platform/transaction failures in your job framework. Log safe identifiers and the failure reason; do not write entire documents, signing URLs, or sensitive merged values into logs. The package's `DocGenController` and `DocGenBulkController` are internal UI controllers, not exported subscriber APIs. `@AuraEnabled` does not make a public controller global. Call the exported service/actions or your own authorized wrapper. ## Build a custom Apex data provider A provider prepares the dataset before Portwood merges it. Use one for calculated values, deliberately shaped reports, or data that the visual query builder cannot express. #### 1. Implement both required methods ```apex global interface DocGenDataProvider { Map getData(Id recordId); List getFieldNames(); } ``` Your class implements `portwoodglobal.DocGenDataProvider`; expose both methods as global. `getData()` supplies values and `getFieldNames()` supplies the authoring field list. The old one-method example was incomplete. Use the complete [KBAccountProvider class](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/apex/KBAccountProvider.cls) and its [metadata file](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/apex/KBAccountProvider.cls-meta.xml). It uses `with sharing` and `WITH USER_MODE`, selects standard Account/Contact fields, limits the Contact query to 100, and implements both methods. The ContactCount is the count of those returned rows, not a claim to count unlimited Contacts. #### 2. Understand the data shape ```apex Map data = new Map{ 'Name' => 'Northstar Bikes', 'Owner' => new Map{'Name' => 'Practice Owner'}, 'Contacts' => new Map{ 'records' => new List{ new Map{'Name' => 'Avery Chen', 'Email' => 'avery@example.com'} } } }; ``` | Data | Template | | --------------------------------- | --------------------------------------- | | Root scalar | `{Name}` | | Nested map | `{Owner.Name}` | | Relationship wrapper with records | `{#Contacts}{Name}: {Email}{/Contacts}` | Inside the loop, `Name` is the Contact's key. Include parent paths and list field paths in `getFieldNames()` so an author can discover them. Keep shape and casing stable as your provider evolves. #### 3. Bind the template Choose **Apex Class (Data Provider)** as its data source and enter `KBAccountProvider`, or set the equivalent Query Config: ```json { "v": 4, "provider": "KBAccountProvider" } ``` Save and activate a version, select a valid sample Account, and preview. In the example, the preview returned Northstar Bikes and two Contacts. With your own sample record, compare the Account name and Contact rows with the record in Salesforce. #### 4. Test your own boundary cases Test an inaccessible record/field, no related rows, null values, many rows, and the intended Flow/bulk path. Keep data selection separate from layout so a template change does not silently widen access. A provider is responsible for sharing, object/field permissions, and any external integration policy. #### Use a map without a provider If your calling process already has the data, use `generatePdfBlobFromData` or `generateAndSaveFromData`. The same root/map/records shape applies. You do not need to insert temporary Salesforce records just to merge calculated values. ## Call Flow actions and signing APIs from Apex The global action classes can be called by subscriber Apex as well as Flow. Build their published request types and inspect the returned result for every input. #### Action directory | Class and entry point | Use | Result to follow | | --------------------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------- | | `DocGenFlowAction.generateDocument(List)` | Normal document generation, optional JSON data and save target | Success/error, ContentDocumentId and ContentVersionId | | `DocGenGiantQueryFlowAction.generateDocument(List)` | Automatic small/giant path selection | Immediate File or jobId plus isGiantQuery | | `DocGenBulkFlowAction.generateBulkDocuments(List)` | Many parent records | jobId and success/error | | `DocGenSignatureFlowAction.generate(List)` | Create a current signing request | Request Id, ordered signer links and success/error | | `DocGenFieldWritebackService.writeBackFields(List)` | Retry completed-request signer-field writeback | Inspect resulting record fields/errors | See the generated [global declarations](#apex-surface) for every published DTO field, and the task articles for the meaning of the Flow inputs. #### Generate through a request object ```apex portwoodglobal.DocGenFlowAction.Request input = new portwoodglobal.DocGenFlowAction.Request(); input.templateApiName = 'KB_Account_Brief'; input.recordId = accountId; input.saveToRecord = true; List results = portwoodglobal.DocGenFlowAction.generateDocument( new List{input}); if (!results[0].success) { System.debug(LoggingLevel.ERROR, results[0].errorMessage); } ``` Run rendering in a supported fresh transaction. A list input is a contract shape, not permission to render an unlimited number of PDFs in one transaction. The Generate Document request above was compiled and executed against the installed subscriber package; it returned success and a File Id. #### Build current signers ```apex portwoodglobal.DocGenSigner signer = new portwoodglobal.DocGenSigner(); signer.name = 'Jordan Rivera'; signer.email = 'jordan@example.com'; // replace with an intended recipient you control for testing signer.role = 'Customer'; // matches {@Signature_Customer} in the practice template portwoodglobal.DocGenSignatureFlowAction.Request input = new portwoodglobal.DocGenSignatureFlowAction.Request(); input.templateApiName = 'KB_Signing_Practice'; input.relatedRecordId = accountId; input.signerRecords = new List{signer}; input.signingOrder = 'Single'; input.sendEmails = false; input.requireEmailVerification = false; // deliberate no-code test; choose your real policy List results = portwoodglobal.DocGenSignatureFlowAction.generate( new List{input}); // Check success/errorMessage before consuming signatureRequestId or signerUrls. ``` Configure the public [signing site](#setup-signatures) first. Setting `sendEmails=false` suppresses invitation delivery; it is not the internal authenticated-preview mode and does not remove the need for email infrastructure if verification is enabled. Signing URLs are credentials: deliver them only to their intended recipients. The signing request shape was also compiled and executed in the subscriber org with invitations and verification disabled. Its link loaded the PDF and both placements in a clean guest browser. That test did not submit the public request or exercise email delivery. #### Avoid legacy-token traps `DocGenSignaturePdfFlowAction.send` is deprecated; use Create Signature Request for new integrations. `DocGenSignatureValidator` can validate both modern signer tokens and legacy request tokens. `DocGenSignatureSubmitter` and `DocGenSignatureFinalizer` only submit/finalize the legacy request-token workflow; successful validation does not make those actions compatible with a modern token. Do not use the submitter/finalizer to inject a captured signature into a current v3 signer token; that is unsupported. Use `DocGenSigner` for the signer collection. The older nested Signer type and parallel legacy lists remain published for compatibility, but the standalone type is the usable choice for new Flow authoring. `DocGenSignaturePreparationController` also has global methods for the authenticated uploaded-PDF preparation UI: context, PDF selection/upload, draft load/save/send. They enforce record/draft ownership and expected revisions. This UI-oriented JSON/revision workflow is more coupled than the service/action APIs; use the packaged sender unless you intentionally own that full preparation experience. ## Use PDF, email, and cleanup helpers These global helpers support specific jobs. Read the input limits before putting one into your process. #### Merge PDF files in order ```apex Blob packet = portwoodglobal.DocGenPdfMerger.mergePdfs( new List{firstPdf, secondPdf}, true); Integer pages = portwoodglobal.DocGenPdfMerger.pageCount(packet); ``` `mergePdfCvs(List, Boolean)` accepts ContentVersion Ids and loads parts incrementally. Passing `true` adds a blank page after every odd-length part, including the last part. Two one-page parts therefore produce four pages. The blank pages carry no page number; the content pages retain numbering baked into their original render. The native merger handles standard uploaded PDFs, including supported compressed object and cross-reference streams. Ordinary AcroForm values are kept under separate field names for each source. Encrypted, signed, XFA and scripted forms are rejected. Catch `DocGenPdfMerger.DocGenPdfMergeException` for unsupported inputs. For exact file-version inputs and a saved File output, use [Merge PDFs in Flow](#merge-pdfs-flow). To check duplex padding, merge two one-page PDFs. The result should have four pages, with the two originals on pages one and three. #### Render a branded email without sending it ```apex Map tokens = new Map{ 'SignerName' => 'Jordan Rivera', 'DocumentTitle' => 'Practice document', 'SignatureUrl' => 'https://example.com/practice' }; portwoodglobal.DocGenEmailTemplateService.RenderedEmail email = portwoodglobal.DocGenEmailTemplateService.render( portwoodglobal.DocGenEmailTemplateService.TYPE_REQUEST, tokens); String subject = email.subject; String html = email.htmlBody; String plainText = email.plainBody; ``` Overloads add `messageOverride`, then `brandId`. `renderSubject(String, Map)` resolves subject tokens. Rendering does not send an email, create a request, or authorize a signing URL. Use the appropriate email type/token contract and a real request's URL when building an actual notification. The rendered subject and body were checked in the fresh org. No email was sent by this rendering test. #### Schedule transient chart/PDF-part cleanup ```apex System.schedule('Portwood transient cleanup', '0 0 * * * ?', new portwoodglobal.DocGenChartCvReaper()); ``` Inspect Scheduled Jobs first so you do not add duplicate schedules. `reap()` is also exported and returns the number cleaned. The current helper targets old, orphan transient `chart_`/`pdfpart_` files, with age/job-state checks and a bounded batch. It is not a general Salesforce Files retention policy. `DocGenEmailTemplateInstall` is the package install handler; `seedDefaults()` is an exported setup utility. Normal document generation does not require calling the install handler yourself. #### Add native AI authoring `DocGenAiProvider` requires `isAvailable()`, `getName()`, and `generateHtml(String)`. The optional Agentforce extension exports `DocGenEinsteinProvider`. Use [Agentforce setup](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/AGENTFORCE_SETUP.md) for entitlement and configuration. The native provider contract uses Einstein/ConnectApi and explicitly excludes HTTP-callout providers. Return a complete HTML document and handle unavailable configuration through `isAvailable()`. ## All exported global Apex declarations This inventory is generated from the same source checkout as the guide. It includes core global types, nested request/result types and fields, interface methods, and the optional Agentforce extension. It gives you an exact place to check an overload or DTO field while using the worked integration articles. **Before you start:** Use the `portwoodglobal` namespace for core types in subscriber Apex. The optional extension requires its own installation/setup. Published legacy members remain in this list; their presence does not make them the preferred API for new work. Read the [action compatibility notes](#apex-actions) and [utility limits](#apex-utilities). A source update that changes an exported declaration makes the generated guide stale until it is rebuilt. Review the related integration article and test your subscriber code against the new released package before marking the next release reviewed. #### DocGenAiProvider Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenAiProvider.cls) ```apex global interface DocGenAiProvider Boolean isAvailable() String getName() String generateHtml(String prompt) ``` #### DocGenBulkFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenBulkFlowAction.cls) ```apex global with sharing class DocGenBulkFlowAction global class Request global Id templateId global String templateApiName global String queryCondition global List recordIds global String sortOrder global String jobLabel global Boolean combinedPdfOnly global Boolean keepIndividualFiles global Boolean duplexPadding global Integer batchSize global class Response global Id jobId global String errorMessage global Boolean success global static List generateBulkDocuments(List requests) ``` #### DocGenChartCvReaper Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenChartCvReaper.cls) ```apex global with sharing class DocGenChartCvReaper implements Schedulable global void execute(SchedulableContext ctx) global static Integer reap() ``` #### DocGenDataProvider Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenDataProvider.cls) ```apex global interface DocGenDataProvider Map getData(Id recordId) List getFieldNames() ``` #### DocGenEmailTemplateInstall Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenEmailTemplateInstall.cls) ```apex global with sharing class DocGenEmailTemplateInstall implements InstallHandler global void onInstall(InstallContext context) global static Integer seedDefaults() ``` #### DocGenEmailTemplateService Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenEmailTemplateService.cls) ```apex global with sharing class DocGenEmailTemplateService global static final String TYPE_REQUEST = 'Signature_Request' global static final String TYPE_REMINDER = 'Signature_Reminder' global static final String TYPE_PIN = 'Verification_PIN' global static final String TYPE_SIGNER_COMPLETED = 'Signer_Completed' global static final String TYPE_ALL_SIGNED = 'All_Signed' global static final String TYPE_DECLINED = 'Signer_Declined' global static final String TYPE_REVOKED = 'Signature_Revoked' global static final String TYPE_COMPLETION = 'Completion_Confirmation' global static final List ALL_TYPES = new List global static final String MODE_MANAGED = 'Managed' global static final String MODE_FULL_HTML = 'Full_Html' global class RenderedEmail global String subject global String htmlBody global String plainBody global static RenderedEmail render(String type, Map tokens) global static RenderedEmail render(String type, Map tokens, String messageOverride) global static RenderedEmail render(String type, Map tokens, String messageOverride, Id brandId) global static String renderSubject(String subjectTemplate, Map tokens) ``` #### DocGenException Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenException.cls) ```apex global with sharing class DocGenException extends Exception ``` #### DocGenFieldWritebackService Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenFieldWritebackService.cls) ```apex global without sharing class DocGenFieldWritebackService global class WritebackRequest global String requestId global WritebackRequest() global static void writeBackFields(List requests) ``` #### DocGenFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenFlowAction.cls) ```apex global with sharing class DocGenFlowAction global class Request global Id templateId global String templateApiName global Id recordId global Boolean saveToRecord global String documentTitle global String outputFormatOverride global String jsonData global class Response global Id contentDocumentId global Id contentVersionId global String errorMessage global Boolean success global static List generateDocument(List requests) ``` #### DocGenGiantQueryFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenGiantQueryFlowAction.cls) ```apex global with sharing class DocGenGiantQueryFlowAction global class Request global Id templateId global Id recordId global Boolean saveToRecord global class Response global Id contentDocumentId global Id contentVersionId global Id jobId global Boolean isGiantQuery global String errorMessage global Boolean success global static List generateDocument(List requests) ``` #### DocGenMigrationRest Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenMigrationRest.cls) ```apex global with sharing class DocGenMigrationRest global static void readConfiguration() global static void createConfiguration() global static void discardStage() ``` #### DocGenPdfMergeFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenPdfMergeFlowAction.cls) ```apex global with sharing class DocGenPdfMergeFlowAction global class Request global List contentVersionIds global String contentVersionIdsText global String documentTitle global Id relatedRecordId global Boolean padOddDocuments global class Response global Id contentVersionId global Id contentDocumentId global Boolean success global String errorMessage global static List mergePdfs(List requests) ``` #### DocGenPdfMerger Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenPdfMerger.cls) ```apex global with sharing class DocGenPdfMerger global class DocGenPdfMergeException extends Exception global static Blob mergePdfs(List pdfs, Boolean padOddDocuments) global static Blob mergePdfCvs(List partCvIds, Boolean padOddDocuments) global static Integer pageCount(Blob pdf) ``` #### DocGenService Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenService.cls) ```apex global with sharing class DocGenService global static Map generatePdfBlob(Id templateId, Id recordId) global static Id generateDocument(Id templateId, Id recordId) global static Id generateDocument(Id templateId, Id recordId, String outputFormatOverride) global static Id generateDocument(Id templateId, Id recordId, String outputFormatOverride, String documentTitle) global static Id generateDocument( Id templateId, Id recordId, String outputFormatOverride, String documentTitle, Id attachmentRecordId ) global static Id generateDocumentFromData(Id templateId, Id recordId, Map preloadedRecordData) global static Map generatePdfBlobFromData( Id templateId, Id recordId, Map preloadedRecordData ) global static Map generatePdfBlobFromData(Id templateId, Map dataMap) global static Id generateAndSaveFromData( Id templateId, Id attachmentRecordId, Map dataMap, String outputFormatOverride ) global static Id generateAndSaveFromData( Id templateId, Id attachmentRecordId, Map dataMap, String outputFormatOverride, String documentTitle ) global static Id generateAndSaveFromData( Id templateId, Id attachmentRecordId, Map dataMap, String outputFormatOverride, String documentTitle, Id fileAttachmentTarget ) ``` #### DocGenSignatureFinalizer Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignatureFinalizer.cls) ```apex global without sharing class DocGenSignatureFinalizer global class FinalizeRequest global String token global String base64Image global static void finalizeSignature(List requests) ``` #### DocGenSignatureFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignatureFlowAction.cls) ```apex global with sharing class DocGenSignatureFlowAction global class Signer global Signer() global String name global String email global String role global Id contactId global class Request global Id templateId global String templateApiName global Id relatedRecordId global List signers global List signerRecords global List signerNames global List signerEmails global List signerRoles global List signerContactIds global Boolean sendEmails global String signingOrder global String emailMessage global String emailSubject global Boolean requireEmailVerification global Boolean prefillSignerEmail global Integer expirationDays global class Result global Id signatureRequestId global List signerUrls global List signerNames global List signerEmails global List signerRoles global String emailStatus global Boolean success global String errorMessage global static List generate(List requests) ``` #### DocGenSignaturePdfFlowAction Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignaturePdfFlowAction.cls) ```apex global with sharing class DocGenSignaturePdfFlowAction global class Request global Id templateId global Id contentVersionId global Id relatedRecordId global List signerRecords global String signingOrder global String documentTitleFormat global class Result global Id signatureRequestId global List signerUrls global List signerNames global List signerEmails global List signerRoles global Boolean success global String errorMessage global static List send(List requests) ``` #### DocGenSignaturePreparationController Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignaturePreparationController.cls) ```apex global with sharing class DocGenSignaturePreparationController global static List searchContacts(Id recordId, String search) global static Map getContext(Id recordId) global static Map uploadPdf(Id recordId, String fileName, String base64Pdf) global static Map selectPdf(Id recordId, Id contentVersionId) global static Map loadDraft(Id recordId, Id draftId) global static Integer saveDraft(Id recordId, Id draftId, Integer expectedRevision, String configJson) global static Map sendDraft(Id recordId, Id draftId, Integer expectedRevision, String configJson) ``` #### DocGenSignatureSubmitter Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignatureSubmitter.cls) ```apex global without sharing class DocGenSignatureSubmitter global class FlowInput global String token global String signatureData global class FlowOutput global Boolean isSuccess global String errorMessage global static List submitSignature(List inputs) ``` #### DocGenSignatureValidator Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSignatureValidator.cls) ```apex global without sharing class DocGenSignatureValidator global class FlowInput global String token global class FlowOutput global Boolean isValid global String errorMessage global String signerName global String documentTitle global String documentUrl global static List validateToken(List inputs) ``` #### DocGenSigner Core · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/force-app/main/default/classes/DocGenSigner.cls) ```apex global class DocGenSigner global DocGenSigner() global String name global String email global String role global Id contactId ``` #### DocGenEinsteinProvider Optional Agentforce extension · [Source](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/agentforce-ext/main/default/classes/DocGenEinsteinProvider.cls) ```apex global with sharing class DocGenEinsteinProvider implements DocGenAiProvider global String getName() global Boolean isAvailable() global String generateHtml(String prompt) global class DocGenAiException extends Exception ``` ## Create the Salesforce signing site A Salesforce Site gives external recipients a public doorway to the signing experience. Each recipient opens their own signing link without a Salesforce login or an individual Portwood license. Your site’s guest user needs Portwood license coverage. **Before you start:** Install Portwood and use a Salesforce administrator account. This walkthrough uses **Salesforce Sites**. If your organization already uses Experience Cloud, follow [the Experience Cloud route](#site-experience-cloud) instead. #### 1. Open Sites 1. Open the gear menu and choose **Setup**. 2. Type **Sites** in Quick Find. 3. Open **Sites** under **Sites and Domains**. 4. If this org has no Salesforce Sites domain, register the intended available domain using Salesforce's on-screen process. Domain selection belongs to your organization's site plan; check it before registering. 5. Click **New**. In the fresh scratch org, Salesforce had already provisioned a Sites domain. A new production org can show a domain-registration step first. Salesforce describes these controls in [Manage Salesforce Sites](https://help.salesforce.com/s/articleView?id=platform.sites_managing_sites.htm&language=en_US&type=5). #### 2. Name and activate the site | Field | Example or choice | | -------------------------- | ------------------------------------------------------------------------------------------------------ | | Site Label | Portwood Signing | | Site Name | Portwood_Signing; check the generated value | | Site Contact | The internal user responsible for this site | | Default Record Owner | An appropriate active internal user | | Default Web Address | A short unused path such as `sign` | | Active | Selected | | Active Site Home Page | Use the lookup to choose `portwoodglobal.DocGenSignature`, or your organization's neutral landing page | | Clickjack Protection Level | Leave the recommended same-origin protection for this standalone signing site | Use the home-page lookup rather than guessing its API spelling. Managed pages appear with the namespace, and typed lookup values can fail to resolve. The home page does not replace the complete signing URL generated for each request. Save. On **Site Details**, copy the HTTPS domain plus the site's path from **Custom URLs**. For example: ```text https://your-domain.my.salesforce-sites.com/sign ``` Your domain will differ. The example is a base address, not a signing link. ![A newly created Salesforce Site shows its active state, home page, and Custom URLs](docs/images/userguide/v3.60/site-details.png) #### 3. Enable the packaged public pages 1. On Site Details, find **Site Visualforce Pages** and click **Edit**. 2. Move these pages into **Enabled Visualforce Pages**: - `portwoodglobal.DocGenSignature` - `portwoodglobal.DocGenSignaturePdf` - `portwoodglobal.DocGenVerify` - `portwoodglobal.DocGenSign` 3. Save. The home page may already be enabled. `DocGenSignaturePrepare` is the authenticated preparation UI used by your internal senders; it is not one of the public pages to add for this setup. ![The enabled-page list includes all four packaged public signing pages](docs/images/userguide/v3.60/site-enabled-pages.png) Salesforce documents the available/enabled list in [Assign Visualforce Pages to a Site](https://help.salesforce.com/s/articleView?id=platform.sites_site_pages.htm&language=en_US&type=5). #### 4. Give this site's guest user the packaged permission set Each site has its own guest user. Assigning a permission set to yourself or a different site's guest will not complete this step. 1. Return to Site Details and click **Public Access Settings**. 2. On the guest profile, click **View Users**. 3. Open the user named for this site, such as **Portwood Signing Site Guest User**. 4. With per-user licensing, find **Managed Packages** on this guest user. Assign an available **Portwood** license if it is missing. A Portwood site license already covers the guest. [See the license assignment screens](#user-licenses) 5. In **Permission Set Assignments**, click **Edit Assignments**. Move **Portwood Guest Signature** to **Enabled Permission Sets** and save. ![Portwood Guest Signature is selected for this site's guest user](docs/images/userguide/v3.60/site-guest-permission.png) Use the packaged permission set as the starting point. Do not grant a guest the Admin permission set or broad Account/Contact access to make signing work. The signing pipeline uses the specific request/link and packaged access controls. #### 5. Tell Portwood where the site lives 1. Open the **Portwood** app and its **Signatures** workspace. 2. Paste the base address into **Signature Site URL**, including your site's path such as `/sign`. 3. Save the setting and click **Re-check Setup**. 4. Follow [Configure signing email](#site-email) for the sender and verification delivery. Do not include `/apex/…`, a token, or a single recipient's signing link in the base setting. #### 6. Prove the public path Create a practice request and open its generated signing link in a private browser window signed out of Salesforce. Check document preview, required fields, consent, submission, request status, and the saved completed file. Once email is configured, repeat with verification enabled and an inbox you control. ![The practice document and its signature/date fields load in a clean public guest browser](docs/images/userguide/v3.60/site-public-preview.png) **You are done when:** The intended public signer can finish the full request. A green setup checklist is a configuration check, not a substitute for this test. ## Use an Experience Cloud signing site Use this route when your organization wants signing served through an Experience Cloud site. The standalone [Salesforce Site walkthrough](#site-salesforce) is the simpler starting point when you do not need a wider portal. **Before you start:** Your administrator owns an active Experience Cloud site, its domain, and its guest-access policy. Experience templates and administrative screens vary; follow Salesforce's [Create an Experience Cloud Site](https://help.salesforce.com/s/articleView?id=networks_creating.htm&language=en_US&type=5) for the site's initial creation and publication. #### Decide how customers will sign | What happens in your community or portal | What you need | | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | A customer opens a private invitation link without logging in to the portal | With per-user licensing, assign a Portwood license to this site’s Salesforce guest user. Public recipients need no individual seat. Assign **Portwood Guest Signature** to the guest user. | | A customer or partner logs in and signs as a member, including inside a Screen Flow | **Authenticated signing requires a Portwood site license.** Give the member Salesforce access to this site, its signing page and the specific Screen Flow. For the embedded signing screen, assign **Portwood Portal Signer**. | | The portal offers both routes | The org’s site license covers the members and the guest user. Configure the guest and member permissions for their respective signing routes. | For a members-only experience, arrange the site license and test the Flow as a customer or partner. [Request an enterprise site-license quote](https://calendar.app.google/HJLhcSFRFDoqxXEM9) · [Add the signing screen to a Flow](#flow-signatures) The steps below configure **public signing links** on an Experience Cloud site. #### 1. Open the site's administration In **Setup → Digital Experiences → All Sites**, open the site's **Workspaces** and administration controls. Confirm that the site is active/published and that the external domain works while signed out. #### 2. Enable the packaged public pages Find this site's guest profile/public access settings. In its **Enabled Visualforce Page Access**, enable the packaged pages `DocGenSignature`, `DocGenSignaturePdf`, `DocGenVerify`, and `DocGenSign` in the `portwoodglobal` namespace. On the guest profile, open **Assigned Users** or **View Users**, then select the site’s guest user. For per-user licensing, confirm **Portwood** under **Managed Packages** on that record. Assign **Portwood Guest Signature** under **Permission Set Assignments**. [Find and license the right user](#user-licenses) #### 3. Allow the public document preview In the site's **Administration → Preferences**, enable: **Let guest users view asset files, library files, and CMS content available to the site**. Without this, the signing shell can load while the PDF says **Document unavailable**. This preference is not a reason to make unrelated Salesforce Files public; verify the actual signing document's token-controlled preview. #### 4. Enter the correct base address In **Portwood → Signatures → Signature Site URL**, use the site's base address with its site path, but remove a trailing `/s`. | Browser's portal address | Portwood base setting | | ----------------------------------------- | --------------------------------------- | | `https://example.my.site.com/customers/s` | `https://example.my.site.com/customers` | Do not append a Visualforce page or signer token. Save and **Re-check Setup**. #### 5. Test outside your admin session Use a practice request and a private browser. Confirm the generated link, PDF preview, signing, and saved output. Then test verification and completion delivery using [Configure signing email](#site-email). If a link opens **Invalid Page**, first check the `/s` suffix, enabled Visualforce pages, active site, and base path. If the page loads but the PDF is unavailable, check the guest content preference and packaged guest permission set. This route was reviewed against the current signing URL logic and existing configuration guidance. The fresh-org hands-on setup used Salesforce Sites; it did not provision every Experience template. ## Configure signing email and verification The public page and the email sender are separate parts of signing setup. A working page does not prove that invitations or verification codes can be delivered. **Before you start:** Use an administrator account and a real sender/inbox controlled by your organization. Domain authentication can require your email or DNS administrator. #### 1. Create the sender address 1. In **Setup**, search for **Organization-Wide Addresses**. 2. Add the intended display name and email address. 3. Make it available to the profiles required by the signing workflow, including the guest completion path where applicable. 4. Open Salesforce's verification message in that inbox and complete verification. 5. Confirm the address is verified and eligible before selecting it in Portwood. A brand can have its own sender, but that address also needs to be verified and usable. An address that an admin can select is not proof that every runtime path can use it. #### 2. Complete Salesforce email prerequisites Check **Setup → Deliverability** and the org's sending-domain verification/authentication requirements. Use your organization's approved sender domain, DKIM and other domain records as required by Salesforce and your email setup. Sandbox/scratch delivery restrictions and unverified domains can prevent mail even when the Portwood settings look complete. Use Salesforce's current [Organization-Wide Addresses documentation](https://help.salesforce.com/s/articleView?id=sf.emailadmin_manage_orgwide_email_addresses.htm&language=en_US&type=5) and [requirements for sending email](https://help.salesforce.com/s/articleView?id=xcloud.security_email_verification_requirements.htm&language=en_US&type=5) for the platform controls. #### 3. Select it in Portwood 1. Open **Portwood → Signatures**. 2. Choose the verified address in **Send Emails From**. 3. Save and click **Re-check Setup**. 4. Set the default email verification, pre-fill, expiration, and reminder choices. 5. Open [Brands and Email Templates](#brands-and-emails) if you want different identities or wording. Check the actual template and send review: template/request overrides can change whether a code is required. Suppressing branded invitations does not suppress required PIN verification emails. #### 4. Test each delivery separately | Test | Check | | ------------------ | ------------------------------------------------------------------------------------------------ | | Invitation | Right sender, subject, brand, recipient, and working link | | Verification code | Code arrives in the expected inbox and unlocks the request | | Sequential signing | Only the currently eligible signer gets the appropriate invitation | | Reminder | Schedule and sender match your intended operation; reminders currently use the org-wide identity | | Completion | Expected recipients receive completion and can access the intended result | Use an inbox you control and a practice document. Open the signing link outside your Salesforce session. Check spam/quarantine and the request's **Email Status** when delivery fails; an already-sent status cannot guarantee that an external mail system placed the message in an inbox. #### Keep a repeatable setup check When changing domains, site URLs, guest users, brands, senders, or verification policy, run the public test again. Record which part failed: link, PDF preview, code delivery, signing, file save, or completion delivery. That makes support much faster than a general “signing does not work.” The fresh knowledgebase org deliberately used no production sender. Site/public signing and email rendering can be tested separately, but actual invitation/PIN/reminder/completion delivery still requires a verified sender and a controlled inbox. ## Collect signer answers and write them back Ask a signer for a PO number, selected date, acknowledgement, or other information while they sign. These are signer inputs, separate from the Salesforce fields merged when the request is created. #### Configure an input 1. Open the template editor and choose **Signer Inputs**. 2. Click **Add Field**. 3. Set the **Label** and **Type**: text, number, date, checkbox, or picklist. Supply choices for a picklist. 4. Choose **Required** if the signer must answer. 5. Copy the generated **Merge Tag**. Its stable key uses letters, numbers, and underscores. 6. Choose **On Certificate** if the answer should appear on the completion certificate. 7. To update Salesforce after signing, select a suitable **Mapped Field** on the related record and enable **Write Back**. 8. Save the intended version and test a practice signing request. #### Place the answer ```text {?poNumber} {?poNumber|N/A} ``` The second form supplies a fallback when no answer is available. Use the key copied from the editor; typing a new key into the document does not create an input. Reserve its own line or table cell for the value so it has room to render without overprinting a static label. The signer fills these fields during signing. Answers can appear in the finished document and, when configured, on the certificate. This feature is separate from mapping an uploaded PDF's AcroForm fields or manually placing signature spots in the uploaded-PDF preparation screen. #### Understand writeback Writeback runs after the completed signed PDF is saved. It updates only fields explicitly mapped and enabled in the template configuration. The guest does not receive general permission to edit the related Account, Opportunity, or other base record. **Writeback supports single-signer requests.** With several signers, answers are captured and attributed on the certificate, but record writeback is skipped because there is no unambiguous single answer for a shared field. Do not design a multi-signer packet expecting the last answer to overwrite Salesforce. Field access, supported value conversion, and validation rules still apply. A failed record update is logged; it does not undo a completed signing request. Check the related record and **Portwood Signature Audits** for writeback failures rather than treating a Signed status as proof of a successful field update. #### Retry a failed update Correct the mapped field, permissions, or validation issue first. The global **Write Back Signer Form Fields** action accepts only the completed request Id and re-derives the allowed fields from its configuration. It does not accept arbitrary field/value instructions from the guest. ```apex portwoodglobal.DocGenFieldWritebackService.WritebackRequest retry = new portwoodglobal.DocGenFieldWritebackService.WritebackRequest(); retry.requestId = completedRequestId; portwoodglobal.DocGenFieldWritebackService.writeBackFields( new List{retry}); ``` The action returns no success DTO and logs failures instead of throwing them back into signing. Verify the target value and audit after a retry. Test an optional blank answer, required answer, invalid value, inaccessible field, validation-rule failure, and multi-signer request before enabling this in a business process. ## Signing email tokens and custom buttons Signing-email tokens belong to the **Email Templates** editor. They are not the document's Salesforce field-query syntax. Their values are supplied by the type of email being sent. #### Choose the email before choosing a token Open **Portwood → Email Templates**, pick the **Brand**, then the email type. The editor offers these insertable tokens for each type: | Email | Editor tokens | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Signature Request | `{SignerName}`, `{SenderName}`, `{CompanyName}`, `{DocumentTitle}`, `{RoleName}`, `{Message}`, `{ActionButton}`, `{DocumentInfo}`, `{SecurityNote}`, `{SignatureUrl}`, `{ExpirationHours}`, `{LogoUrl}` | | Signature Reminder | `{SignerName}`, `{SenderName}`, `{CompanyName}`, `{DocumentTitle}`, `{RoleName}`, `{Message}`, `{ActionButton}`, `{DocumentInfo}`, `{SecurityNote}`, `{SignatureUrl}`, `{ExpirationHours}`, `{LogoUrl}` | | Email Verification Code | `{VerificationCode}`, `{Pin}`, `{ExpirationMinutes}`, `{CompanyName}`, `{LogoUrl}` | | Signer Completed | `{SignerName}`, `{RoleName}`, `{RequestId}`, `{CompanyName}`, `{LogoUrl}` | | All Signatures Complete | `{RequestId}`, `{CompanyName}`, `{LogoUrl}` | | Signer Declined | `{SignerName}`, `{RoleName}`, `{Message}`, `{RequestId}`, `{CompanyName}`, `{LogoUrl}` | | Signature Request Revoked | `{SignerName}`, `{SenderName}`, `{CompanyName}`, `{DocumentTitle}`, `{RoleName}`, `{Message}`, `{RequestId}`, `{LogoUrl}` | | Completion Confirmation | `{SignerName}`, `{DocumentTitle}`, `{CompanyName}`, `{LogoUrl}` | `{CompanyName}`, `{BrandColor}`, and `{LogoUrl}` are resolved through branding. `{Message}` is supplied by the send/template message when that email supports it. Missing or unknown ordinary tokens resolve to empty; a value visible in a generic sample preview is not proof that a production sender supplies it for every email type. In particular, do not assume `{DocumentTitle}` is supplied to every sender-notification type. Values in HTML bodies are HTML-escaped. Shared assets use the separate `{%asset:asset-key}` syntax to resolve to a public image URL. In an email, write the `` yourself; document asset tags use a different image-embedding path. #### Upgraded from an earlier version? Add the Signature Request Revoked type The **Signature Request Revoked** email goes to signers who had not signed when a request is revoked. If this email type is missing from the editor after an upgrade, the built-in notice still sends. An administrator can [add the missing email type](#upgrade-portwood) to customize the wording. To customize the revoke email in an upgraded org: 1. In Setup, open **Object Manager → Email Template → Fields & Relationships → Type**. 2. Under **Values**, add a value with the API name `Signature_Revoked` and the label `Signature Request Revoked (to signers)`. The API name must match exactly. 3. Open **Portwood → Email Templates**, choose **Signature Request Revoked**, edit it, and save. Every other email type can be customized without this step. #### Understand the widgets | Widget | Creates | Raw values to use for your own design | | -------------------- | ------------------------------------- | ------------------------------------- | | `{ActionButton}` | Branded Review & Sign button | `{SignatureUrl}` | | `{DocumentInfo}` | Document/role callout | `{DocumentTitle}`, `{RoleName}` | | `{SecurityNote}` | Expiry note and fallback signing link | `{SignatureUrl}`, `{ExpirationHours}` | | `{VerificationCode}` | Large verification-code block | `{Pin}`, `{ExpirationMinutes}` | The widget's wording and inline styles are generated. A surrounding wrapper can change spacing, but it does not reliably rename or recolor the widget itself in email clients. Replace the widget with your own HTML when you need different wording. Keep the matching raw tokens so the real link or code is still present. #### Example: a button with your own label Use **Full custom HTML** when you want the entire email layout under your control: ```html
Review your proposal

This link expires in {ExpirationHours} hours.

If the button does not work, open {SignatureUrl}.

``` Use this on a request/reminder email that carries a signing URL. A custom verification email instead needs `{Pin}` and `{ExpirationMinutes}`. Never replace the real URL with the website homepage or a sample link from the preview. #### Message and subject precedence For supported single-template sends, the send-time custom message wins, then the template's **Default Email Message**, then the generic email wording. A send-time custom subject can also override that send's saved subject. Check packet/bulk sends separately; they use their saved email configuration. Choose the email type and brand, inspect the live preview, then use **Send Test** to an inbox you control before customer delivery. Public image access and a verified eligible sender remain necessary. The global `DocGenEmailTemplateService.render()` helper renders content; it does not send or invent request-specific tokens. ## Follow asynchronous jobs from Flow or Apex An accepted background job is not a finished document. Store the returned **Job ID** and wait for the job's terminal state before using a File or telling someone generation is complete. #### Read the actual job record In subscriber Apex and Flow, use **Portwood Job** (`portwoodglobal__DocGen_Job__c`) with the access granted to the running user. These are useful API fields: | Field | Meaning | | -------------------------------------------------------------------- | --------------------------------------------- | | `portwoodglobal__Status__c` | Persisted job state | | `portwoodglobal__Total_Records__c` | Intended record count | | `portwoodglobal__Success_Count__c`, `portwoodglobal__Error_Count__c` | Outcome counts | | `portwoodglobal__Error_Log__c` | Recorded error details | | `portwoodglobal__Merged_PDF_CV__c` | Combined output ContentVersion, when produced | ```apex portwoodglobal__DocGen_Job__c job = [ SELECT portwoodglobal__Status__c, portwoodglobal__Success_Count__c, portwoodglobal__Error_Count__c, portwoodglobal__Merged_PDF_CV__c, portwoodglobal__Error_Log__c FROM portwoodglobal__DocGen_Job__c WHERE Id = :jobId WITH USER_MODE LIMIT 1 ]; ``` `DocGenBulkController.getJobStatus()` is a package-internal UI endpoint, not a subscriber Apex API. Use the job record or your own authorized wrapper around its query. #### Distinguish persisted states from screen labels **Draft**, **Harvesting**, **Processing**, **Stitching**, and **Merging** describe preparation or work still in progress. **Completed**, **Completed with Errors**, and **Failed** are terminal outcomes; inspect counts and logs before deciding whether your business process succeeded. Some screens can use friendlier progress labels; do not build a status comparison against a word that is not actually stored on the record. A completed individual-file run may have no combined output Id. Giant-query recovery can launch separate child jobs; the original batch's terminal status does not mean every recovery child has finished. #### Refresh in a screen Flow 1. **Get Records** for the returned Job ID. 2. Use a **Decision** for Completed, Completed with Errors, and Failed. 3. For a nonterminal state, show a **Screen** containing the status and a **Refresh** navigation choice. 4. Connect the refresh route back to Get Records so it re-reads the job. 5. Provide an exit choice; the user does not need to keep a browser open for the job to run. Do not create a tight Get Records/Decision loop with no screen or asynchronous boundary. It repeats in one transaction and can consume the query limit without giving the background job time to finish. Screen Flows do not support a Wait element. For unattended processing, choose an automation pattern compatible with its Flow type, such as a record-triggered Flow on the job's completion update, or an autolaunched Flow with a supported Wait configuration. A record-triggered Flow does not simply gain a generic Wait element; check Salesforce's [Flow types](https://help.salesforce.com/s/articleView?id=sf.flow_concepts_type.htm&language=en_US&type=5) and [Wait considerations](https://help.salesforce.com/s/articleView?id=platform.flow_considerations_design_pause.htm&language=en_US&type=5). #### Handle partial success and recovery For supported Individual Files runs, oversized records can be queued for giant-query recovery. The current batch caps automatic recovery at **100 records** and records any overflow for manual handling. A combined packet is not automatically reconstructed from recovery results. Confirm the correct parent/child job outputs before retrying failed records; rerunning the whole original filter can duplicate successful Files. ## Query configuration formats and aliases V1, V2, and V3 describe Salesforce record queries. V4 binds a custom provider or the special Flow JSON source. Use the visual V3 builder for new record-query templates unless a specific integration needs a different format. #### V1 — Legacy flat string Plain field/subquery selection string. Use V3 when you need a richer tree or explicit child configuration. ``` Name, Industry, (SELECT FirstName, LastName FROM Contacts) ``` Detected when the config does NOT start with `{`. #### V2 — JSON flat (junction support) Adds junction-object support for many-to-many (e.g., Account ↔ Contact via AccountContactRelation). ```json { "v": 2, "baseObject": "Opportunity", "baseFields": ["Name"], "parentFields": ["Account.Name"], "children": [{ "rel": "OpportunityLineItems", "fields": ["Name"] }], "junctions": [ { "junctionRel": "OpportunityContactRoles", "targetObject": "Contact", "targetIdField": "ContactId", "targetFields": ["FirstName"] } ] } ``` #### V3 — Query tree (multi-object, any depth) Preferred. Tree of nodes — each node is one SOQL query, stitched into the parent's data map via `lookupField`. ```json { "v": 3, "root": "Account", "nodes": [ { "id": "n0", "object": "Account", "fields": ["Name"], "parentFields": ["Owner.Name"], "parentNode": null, "lookupField": null, "relationshipName": null }, { "id": "n1", "object": "Contact", "fields": ["FirstName"], "parentFields": [], "parentNode": "n0", "lookupField": "AccountId", "relationshipName": "Contacts" }, { "id": "n2", "object": "Opportunity", "fields": ["Name", "Amount"], "parentFields": [], "parentNode": "n0", "lookupField": "AccountId", "relationshipName": "Opportunities" }, { "id": "n3", "object": "OpportunityLineItem", "fields": ["Quantity"], "parentFields": ["Product2.Name"], "parentNode": "n2", "lookupField": "OpportunityId", "relationshipName": "OpportunityLineItems" } ] } ``` #### Using the visual builder The visual query builder walks your schema like a tree: start from the base object, tick fields (blue pills), climb into **+ parent lookup**, and expand **+ related list** child sections — each child with its own Tag name, Filter (WHERE), Sort by, and Limit. It writes a V3 config. As of v3.37 the same builder appears everywhere a query gets built: **Edit Template → Query Configuration**, the **designer's Query panel**, and the **Generate-with-AI** step. **Multi-hop parent traversal (v1.97+).** On any object's `parentFields` panel, expand a lookup and the builder now recurses into the parent's lookup tree — for example, on an Opportunity tab, expand `Account` → `Parent` → `Owner` → pick `Name`, and the resulting merge tag is `{Account.Parent.Owner.Name}`. The recursion is capped at 5 hops to keep schema-load latency bounded. Each hop loads its target object's fields lazily on expand. Use this when the data you need lives more than one lookup away from the base object and you don't want to compose `parentFields` paths by hand. For direct JSON editing or V1 legacy configs, toggle **Manual Query** mode and the older `docGenQueryBuilder` appears. #### Per-child filters, order by, limit Each V3 child node supports: - `fields`: scalar fields to SELECT - `parentFields`: dotted lookup fields (e.g., `Product2.Name`) - `where`: optional `WHERE` clause (sanitized for SOQL injection) - `orderBy`: optional `ORDER BY` (sanitized) - `limit`: optional `LIMIT` Applies to both sync and giant-query paths. #### Apex Data Provider (V4 — class-backed templates) When the data you need to render isn't an SObject — external API responses, computed totals, cross-object aggregations, anything SOQL can't reach — implement the `portwoodglobal.DocGenDataProvider` interface in your org and bind a template to that class. The merge engine calls your class at render time and uses whatever Map you return. ##### Step 1 — write the provider class in your org ```apex /** Subscriber-side example. Deploy to your org after installing Portwood. */ global with sharing class KBAccountProvider implements portwoodglobal.DocGenDataProvider { global Map getData(Id recordId) { Account account = [ SELECT Name, Industry, Phone FROM Account WHERE Id = :recordId WITH USER_MODE LIMIT 1 ]; List contacts = new List(); for (Contact contact : [ SELECT Name, Email, Title FROM Contact WHERE AccountId = :recordId WITH USER_MODE ORDER BY Name LIMIT 100 ]) { contacts.add( new Map{ 'Name' => contact.Name, 'Email' => contact.Email, 'Title' => contact.Title } ); } return new Map{ 'Name' => account.Name, 'Industry' => account.Industry, 'Phone' => account.Phone, 'ContactCount' => contacts.size(), 'Contacts' => new Map{ 'records' => contacts } }; } global List getFieldNames() { return new List{ 'Name', 'Industry', 'Phone', 'ContactCount', 'Contacts.Name', 'Contacts.Email', 'Contacts.Title' }; } } ``` The sample deliberately returns at most 100 Contacts; its count reflects those returned rows. For a minimal deployed-and-executed example, use [KBAccountProvider](#apex-data-provider). Two methods are required, both `global`. `getData` returns a `Map`; `getFieldNames` returns the list of merge tags shown in the wizard. The interface lives in the managed package — reference it with the full namespace: `portwoodglobal.DocGenDataProvider`. ##### Step 2 — bind a template to the class In the Portwood app → New Template: 1. **Step 1 — Data Source**: pick **Apex Class (Data Provider)** instead of Salesforce Record. 2. **Data Provider Class**: search for your class name (e.g., `KBAccountProvider`). The picker filters to classes implementing `portwoodglobal.DocGenDataProvider`. Select yours. 3. The wizard validates the class, calls `getFieldNames()`, and displays the available merge tags. 4. **Step 2** lands directly on the connected-provider view. Compose your template body using the merge tags as you would for any other template. 5. **Step 3** — review and save. Behind the scenes the template's `Query_Config__c` becomes `{"v":4,"provider":"KBAccountProvider"}`. You can also flip an existing SOQL-backed template to v4 from the **Edit modal → Query Configuration → Use Apex data provider** link. ##### Step 3 — generate Same as any template. The Portwood app's Generate button, the **Generate Document** Flow action, the Apex `DocGenService.generateDocument()` API — all of them detect the v4 binding automatically and call your class. ```apex // From Apex — exactly the same call shape as a SOQL-backed template Id contentDocId = portwoodglobal.DocGenService.generateDocument(templateId, accountId, null); ``` ##### Common patterns - **External callout**: do the callout in `getData`, parse the response, return the parsed Map. Bear in mind callouts subject to governor limits and DML-before-callout rules. - **Cross-object aggregations**: query whatever you need, build aggregates in Apex, expose them as merge tags. - **Custom Metadata-driven**: read Custom Metadata Type records to resolve the data shape dynamically. - **Standalone (no recordId)**: ignore the `recordId` parameter and return data assembled from elsewhere. Useful for "render a report for the current user" templates. If you don't want template-side binding at all — the data is already in a Flow variable or an Apex wrapper — use **runtime data injection** instead: the **Generate Document** Flow action accepts a `JSON Data` invocable variable, and `DocGenService.generatePdfBlobFromData(templateId, dataMap)` accepts an Apex Map directly. Same merge engine, same tags, no class to write. ##### 6.6.1 JSON Data (from Flow) — template authoring mode When a template will _only_ ever receive its data from a Flow via `DocGenFlowAction.jsonData`, pick **JSON Data (from Flow)** as the Data Source in Step 1. The wizard then skips the Base Object picker, the SOQL query builder, and the Apex Provider class picker — there's nothing to configure between naming the template and uploading the document. Behind the scenes the template stores `Base_Object_API__c = 'FlowJsonData'` (a sentinel value) and `Query_Config__c = {"v":4,"source":"flowJsonData"}`. The sentinel keeps the template invisible to the standard record-page Generate-Document launcher (whose query is `WHERE Base_Object_API__c = :objectApiName`) — JSON Data templates are intentionally Flow-only. To invoke one, pass `jsonData` into the **Generate Document** Flow action; the merge engine resolves `{Field}`, `{Parent.Field}`, and `{#Items}…{/Items}` against your JSON shape just like any other template. --- ## Recipes from a first letter to a signed packet Build a client service packet in stages. The first exercise needs one Account and permission to create an HTML template. For the later exercises, use a sandbox where you can manage templates, run a Screen Flow and inspect its records. Use fictional records and signers for practice. [Explore finished quotes, renewal briefs and scannable work orders in the design studio.](#document-studio) For a signing example, [see the buttons the signer uses](#event-signing-journey) or [build the experience in Salesforce](#signing-handoff-setup). | Start with | Build this | Check your result | | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | One Account | [A one-field welcome letter](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/account-letter.html) | The PDF heading contains the Account name. | | Related Opportunities | [A paginated service schedule](#css-print-lab) | The column labels repeat and the final line appears once. | | Shared language | [A versioned handoff clause](#shared-content) | Two templates using the same key pick up the new active text. | | A fillable PDF | [A fixed acceptance form](#fillable-pdf) | The account name is visible and the flattened output has no editable widget. | | Two existing Salesforce Files | [An ordered PDF packet](#merge-pdfs-flow) | Both source documents appear in order in a new File. | | A signed-in customer | [Acceptance inside a Screen Flow](#flow-signatures) | The Flow advances after the component confirms the outcome. | | A signer using the signing site | [A navigation link in a Screen Flow](#signing-site-handoff) | The intended signer opens the site and the interview can check the request again. | | Approval or signing activity in another process | [An event-driven signature workflow](#signing-events) | One approval produces one request and a completed agreement produces one downstream action. | #### Generate the one-field letter 1. Download the letter above using GitHub's **Download raw file**. In Portwood, choose **New Template → Bring an Existing Template**. Choose **Salesforce Record (SOQL)**, **Account**, and **HTML**. 2. Select **Name** in the data picker and upload the HTML body. Save the template and select an Account you can read. 3. Generate the PDF. A record named **Alder Works** should produce **Welcome, Alder Works**. Try a second account before moving on. ![The generated welcome letter shows the Account name where the template had {Name}.](docs/images/userguide/v3.64/welcome-letter.png) The whole binding is `

Welcome, {Name}

`. HTML controls how the heading looks. The query supplies the value. Adding a field in just one of those places leaves part of the job unfinished. For smaller pieces to copy into your own design, including barcodes, headers, totals and signature lines, use the [HTML recipe collection](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/reference/html-recipes.md). For a document with your own fields, start from the [AI authoring workflow](#ai-authoring). Compare your result with the [finished welcome letter](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/account-letter.pdf). To practice merging, pair it with the [flattened service acceptance PDF](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/acceptance/flattened-acceptance.pdf). ## Start with a finished design Start with a file someone actually needs. Open one of these finished PDFs, try its links or scan its equipment labels, then take the HTML and data into your own org. | Build this | Try this in the finished file | Make it your own | | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | | [Commercial proposal](https://portwood.dev/demos/studio/field-quote.pdf) | Click **Harbor reserve** on the cover. Find the battery options, then jump back to the contents. | [Nested pricing tables](#cpq-quote) · [Contents, links and watermarks](#print-navigation) | | [Renewal decision brief](https://portwood.dev/demos/studio/renewal-brief.pdf) | Read the recommendation, then find the team whose adoption is bringing the account below target. | [Design a brief that changes with the data](#renewal-decision) | | [Field-service sheet](https://portwood.dev/demos/studio/service-sheet.pdf) | Scan either equipment card. Its QR code contains the asset identifier printed directly below it. | [Make a scannable service sheet](#service-sheet) | A signer can also move from a Salesforce Screen Flow to a document prepared in the background. [Build the event-driven signing handoff](#event-signing-journey). [Watch the studio chapters](https://portwood.dev/demos/portwood-3.64-demo.html?chapter=give-the-buyer-a-contents-page) to follow a buyer into the quote, a technician to the work order, and a signer through the Flow. #### Run a design someone has already set up Open **Guide · Try a document design** from the page your admin provided. An admin can also open it from **Setup → Flows** and select **Debug**. Leave rollback mode off if you want to keep the generated file. Choose **Renewal decision brief**, then **Generate PDF**. The practice Flow includes fictional customer data. Try another design after you finish the first. ![Choose one of the three designs and select Generate PDF.](docs/images/userguide/v3.64/sample-select.png) On the next screen select **Open your generated PDF in Salesforce Files**. In the renewal brief, look for the recommendation to **Book an adoption review**. If a design fails, check that its template is active and its API name matches the table below. ![After generation, the screen links directly to the new Salesforce File.](docs/images/userguide/v3.64/sample-file.png) #### Put one design in your own sandbox You can build the same experience from the Salesforce screens. [Download the design files](https://portwood.dev/demos/studio/document-studio.zip), unzip them, and pick one matching HTML and JSON pair. The HTML is the layout. The JSON contains the sample customer and figures. Start with `renewal-brief.html` and `renewal-brief.json`. The file ending in `-reading.html` is the already-filled reading copy. 1. In **Portwood → My Templates**, select **New Template → Bring an Existing Template**. Enter a name people will recognize. In **API Name**, use the matching value below if you also want the included practice Flow to find it. 2. Under **Data Source**, select **JSON Data (from Flow)**. Set **Type** to **HTML** and **Output Format** to **PDF**. Select **Next → Create Template**. ![Select JSON Data (from Flow) when the Flow supplies the customer and figures.](docs/images/userguide/v3.64/choose-json.png) ![With HTML as the template type and PDF as the output, the document’s print styling comes from the uploaded HTML.](docs/images/userguide/v3.64/html-output.png) | Design | HTML and JSON filenames start with | API name used by the practice Flow | | ---------------------- | ---------------------------------- | ---------------------------------- | | Commercial proposal | `field-quote` | `Guide364_Studio_field_quote` | | Renewal decision brief | `renewal-brief` | `Guide364_Studio_renewal_brief` | | Field-service sheet | `service-sheet` | `Guide364_Studio_service_sheet` | 3. The template editor opens. Under **Upload New Version**, select **Choose File**, choose the template HTML and select **Save as New Version**. In **Your Templates**, check that the version is active. Keep its API name for the next step. ![Choose File accepts a template HTML file or a Google Docs web-page ZIP.](docs/images/userguide/v3.64/upload-html.png) #### Build a button that generates your design 1. In **Setup → Flows**, select **New Flow → Screen Flow**. Select **+ → Screen**, add **Display Text** with a short invitation to generate the design, and change the screen’s **Next** button label to **Generate PDF**. 2. Open **Toolbox → Manager → New Resource**. Choose **Text Template**, give it the API name `SampleData`, and select **View as Plain Text**. Open the matching JSON file in a text editor, copy its entire contents into the body and select **Done**. 3. Under the first screen, select **+**. Search **Generate Document**. Some orgs offer several actions with that name. Choose the Portwood action whose description starts **Generates a document (PDF, DOCX, PPTX, XLSX)**. Its inputs include both **JSON Data** and **Template API Name**. Give the action a label such as **Make the renewal brief**. 4. Paste the active template’s API name into **Template API Name**, select **SampleData** for **JSON Data**, enter **PDF** for **Output Format Override**, and set **Save to Record** to **False**. You can leave **Record ID** blank for this standalone sample. The working three-design example below calls its JSON resource **Payload**. ![The Portwood action takes the JSON text resource, PDF output and the Save to Record choice.](docs/images/userguide/v3.64/generate-json.png) 5. After the action add a **Decision**. For success, select the action’s **Success** output and compare it to **True**. On that branch add a **Screen** with **Display Text** telling the person to open **Files → Owned by Me** and look for the new PDF. On the default branch, display the action’s **Error Message**. Connect the action’s **fault** path to a screen that displays the **Fault Message**. 6. **Save** the Flow and select **Debug**. Leave rollback mode off, select **Generate PDF**, then open the new File in Salesforce. Compare its recommendation and figures with the finished example. To attach a real document to a record, pass that record’s ID and turn **Save to Record** on. [Generate a document from a record-triggered Flow](#flow-generate) For real orders, supply the same data shape from your own records or an Apex data provider. The sample keys are names you and the HTML share. [Choose a data source](#custom-data) #### Brief your AI like a designer Give the assistant your data shape, the sample HTML, and a change you can recognize in the finished document. For the proposal, try this request. > Adapt the proposal for a purchasing manager. Keep the quoted net prices, currency and section IDs. Give optional services their own panel, keep one-time charges separate from monthly charges, and make the contents links follow their sections even when pricing spills onto another page. Return one HTML file and tell me which three things to check in the PDF. For a renewal brief, describe what should happen when usage is missing. For a work order, specify the actual identifier a technician should scan. Open the generated file and try that task before you save the new template version. [Download the AI authoring reference](https://portwood.dev/demos/studio/portwood-authoring-context.md) #### Give readers a text edition Each sample also has an HTML reading copy with a document language, headings, labeled prices or usage figures, and the equipment identifiers in text. These are filled examples you can open in a browser or use with a screen reader. [Read the proposal](https://portwood.dev/demos/studio/field-quote-reading.html) · [Read the renewal brief](https://portwood.dev/demos/studio/renewal-brief-reading.html) · [Read the work order](https://portwood.dev/demos/studio/service-sheet-reading.html) The three generated PDFs contain selectable text and lack PDF structure tags and document-language metadata. If your customer requires a tagged PDF, check the exported file’s tags, language, reading order, link names and table headers with your accessibility tools, and test the file with their assistive technology. Share the text edition alongside the visual copy. ## Build a linked contents page and a draft watermark Give the reader shortcuts through a long PDF. In the finished proposal, every entry on the cover links to the named section. The dotted leaders end in the current page number. The draft copy also carries its quote number on every page. [Open the finished proposal](https://portwood.dev/demos/studio/field-quote.pdf) · [Read the text edition](https://portwood.dev/demos/studio/field-quote-reading.html) · [Download the design files](https://portwood.dev/demos/studio/document-studio.zip) [View HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/field-quote.html) · [View data](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/field-quote.json) ![The actual proposal cover with a linked table of contents, dot leaders, quoted amounts and a draft mark](docs/images/userguide/v3.64/quote-contents.png) #### Create an entry and its destination Put this link on the contents page. Give the section heading the matching ID. Keep the ID unique across the document. ```html

Configured pricing

Return to contents ``` Give your contents heading `id="contents"` for the return trip. For repeated sections, use a short permanent key for each item. The sample uses `href="#bundle-{Key}"` in the contents and `id="bundle-{Key}"` on the matching bundle. Two products can have the same display name and still need different keys. Gate an optional entry and its destination with the same condition. #### Let the renderer calculate the page ```css .contents a { display: block; text-decoration: none; } .contents a:after { content: leader('.') target-counter(attr(href), page); } .section { page-break-before: always; } ``` The link supplies the destination. The CSS adds the dotted line and the page where that destination actually landed. In the supplied PDF, **Commercial terms** is on page 4. We added 42 component lines and generated again. The terms moved to page 7 and the contents entry and link moved with them. This is a contents page inside the PDF. Open the downloaded file in a PDF reader to test a jump in each direction. #### Print a watermark from HTML For review copies, put a fixed element near the start of the body. Bind the optional block to a Boolean and print a record-specific value in the mark. ```html {#IsDraft}
DRAFT PRICING · {QuoteNumber}
{/IsDraft} ``` ```css .stamp { position: fixed; bottom: 0; right: 0; font: bold 9pt Helvetica; letter-spacing: 1pt; color: #674329; border: 1pt solid #c19a72; padding: 3pt 7pt; background: #fff8ea; } ``` The proposal puts the stamp at the bottom of the printable area and its folio in the bottom page margin. `IsDraft: true` printed the stamp on all four pages. With `false`, the longer release copy had no draft stamp. Reserve that corner so the mark has room when a table grows. For diagonal artwork or a full-bleed letterhead, upload a pre-sized image under **Watermark / Background**. [Use page artwork](#page-layout) #### Add running folios ```css @page { size: Letter; margin: 0.65in 0.72in 0.85in; @bottom-right { content: counter(page) ' / ' counter(pages); } } ``` The sample supplies its own page CSS and leaves Portwood’s separate Header HTML and Footer HTML empty. If your existing template already has a branded footer, use its [running footer recipe](#running-headers-footers) and choose one place to draw the page number. To try this with your own data, start with [Generate a studio sample](#document-studio). ## Build a quote with nested bundle pricing A buyer needs to see which options belong to each configured product and what they cost. This quote gives each bundle an outer table, then prints the components in a smaller table inside it. A separately priced inspection stays beside the Harbor bundle and out of the order total. [Open the example quote](https://portwood.dev/demos/studio/field-quote.pdf) · [Read the text edition](https://portwood.dev/demos/studio/field-quote-reading.html) · [Download the design files](https://portwood.dev/demos/studio/document-studio.zip) [View HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/field-quote.html) · [View data](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/field-quote.json) ![The generated pricing schedule with two bundles, nested component tables, separate subtotals and an optional service](docs/images/userguide/v3.64/quote-pricing.png) #### Bring the quote into the right shape Use your quoting system’s approved, already-priced values. For each bundle, supply its key and display name. Put included lines under its `Components.records` and unselected optional offers under `AddOns.records`. Include `totalSize` so an empty options list suppresses its panel. The [sample data](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/field-quote.json) shows each collection in full. | The buyer sees | What your Flow or provider supplies | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | Configuration | One bundle per parent line, in selling order, with a stable key for the contents link. | | Included items | Each child of that parent, with SKU, description, quantity, list unit price, discount and the net line total. | | Options | Separately quoted extras. A selected option that is already included in the bundle price should have one place in your total. | | Commercial summary | Currency, approved one-time net, recurring price per billing period and payment installments. Keep internal cost and margin out of the payload. | For Salesforce CPQ, save the priced quote first. Start with its lines and inspect the **Required By** relationship to identify an option’s parent. A quote line group is a presentation grouping and can contain several independent bundles. Confirm how your org prices bundled options, prorates subscriptions and rounds line totals. The sample works without installing CPQ. Map your org’s prices into the sample shape. [Salesforce’s Required By field](https://help.salesforce.com/s/articleView?id=000382714&language=en_US&type=1) · [Generate from prepared data](#custom-data) #### Nest the component table Paste the full example to keep the styling. The short version below shows where to open and close both loops. ```html {#Bundles}

{Name}

Component Net
{#Components}{Description} {Net:#,##0.00}{/Components}

Bundle subtotal · {SUM:Components.Net:#,##0.00}

{/Bundles} ``` The outer loop wraps the entire bundle table. The inner loop opens and closes in the component row, so that row repeats inside its own bundle. Put the subtotal outside the component row while the bundle is still in scope. Keep short component rows together and let long bundles flow over the page. For large schedules, inspect the continuation page and its header. [Repeating table headings](#repeat-table-headers) #### Reconcile the order before sharing In the sample, Atlas totals **6,540.00** and Harbor totals **4,130.00**. The cover shows **USD 10,670.00 one time** and **USD 120.00 per month**. The **450.00** optional inspection is separate. On the last page, the three one-time installments add back to **10,670.00**. If your CPQ parent already carries the price of its children, print the parent net as the bundle subtotal. Summing the parent and those same included children would charge twice. Try a bundle with no options, a second bundle with its own components, and one bundle big enough to cross a page. Then follow the cover links to both configurations. [Try the sample in Salesforce](#document-studio) #### Send this exact quote for signature 1. Once the quote is approved, generate the final PDF with `IsDraft` set to `false`. In the Portwood **Generate Document** action, pass the approved **Quote record ID**, the priced **JSON Data**, and **Save to Record = True**. Give the file a recognizable title with the quote number and revision. 2. On that quote, open **Files** and check the PDF and amount. In **Portwood Signature Sender**, choose **New signature request → Salesforce file**, then select that exact revision. Assign a signature field to each recipient, review the pages and send. [Prepare a finished PDF for signature](#sign-uploaded-pdf) 3. Open the request to check its status and retrieve the signed PDF and certificate. The event-driven Screen Flow prepares its own receipt-backed agreement. Use the Salesforce File route above when the buyer must sign the exact approved pricing PDF. [Find the signed file](#manage-signatures) · [Build the event-driven handoff](#event-signing-journey) ## Design a renewal brief that recommends a next step An account owner wants to know what to do before a renewal meeting. This one-page PDF starts with a recommendation, backs it with the account’s contract and usage figures, and shows which team needs attention. [Open the decision brief](https://portwood.dev/demos/studio/renewal-brief.pdf) · [Read the text edition](https://portwood.dev/demos/studio/renewal-brief-reading.html) · [Download the design files](https://portwood.dev/demos/studio/document-studio.zip) [View HTML](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/renewal-brief.html) · [View data](https://github.com/Portwood-Global-Solutions/Portwood/blob/main/docs/knowledgebase/examples/document-studio/renewal-brief.json) ![Renewal decision brief showing the account recommendation, contract value, service cases and team adoption bars](docs/images/userguide/v3.64/renewal-decision.png) #### Make the decision before you write the headline The sample’s teams have **72 active seats out of 100 licensed**. The account target is **80%**, so the recommendation is **Book an adoption review**. Calculate the overall rate from the total seats. An unweighted average of the team percentages gives a different answer. Have the Flow or provider supply `HasUsage`, `AtTarget`, `Adoption` and `Threshold` together. Set `HasUsage` to false for a missing reporting period or a zero denominator. Set `AtTarget` from the data source’s comparison of the measured rate and the account’s agreed threshold. Keep that logic where the business rule lives. | Input state | What the reader sees | | ----------------------------------- | ------------------------------------------------------------------------------ | | Usage is available and below target | **Book an adoption review**, with the agreed threshold and the team breakdown. | | Usage meets or exceeds target | **Prepare renewal terms**, with the same underlying measurements. | | No usable measurement | **Request usage data** and an **Unknown** metric. The team chart is omitted. | #### Print a bar the reader can check The bar is ordinary HTML. The data supplies a numeric percentage between 0 and 100. Give the track a fixed height and print the value alongside it so the document still makes sense in grayscale. ```html
{#Teams}{Name} {Active} / {Licensed} {Percent}%
{/Teams}
CLIENT SERVICES ACCOUNT REVIEW

{Name}

Here is the work planned for your account. Use the reference number when discussing a service line.

Service schedule

Ref. Service line Estimate
{#Opportunities}{RowNumber} {Name} {Amount:#,##0.##}{/Opportunities}

Combined estimate   {SUM:Opportunities.Amount:#,##0.00}

Handoff and acceptance

Review the schedule with your account team. Reference numbers match the order in the service schedule.

{%snippet:guide-service-handoff}
``` ## footer.html ```html
Client services · Service review
Page of
``` ## handoff-fragment.html ```html

After acceptance, our service coordinator will arrange a handoff with {Name}.

``` ## portfolio-brief.html ```html Portfolio review
CLIENT SERVICES   /   PORTFOLIO REVIEW

{Name}

Engagements by stage and the value of work under review.

Engagements{COUNT:Opportunities} Combined estimate{SUM:Opportunities.Amount:#,##0.00}

Stage distribution

{Chart:Opportunities:StageName:bar}

Review note

{#IF Opportunities.totalSize != 0}The following schedule groups engagements by stage. Reference numbers restart in each group.{:else}There are no engagements in the selected data.{/IF}

ACCOUNT DETAIL
{#GroupBy Opportunities by StageName}

{GroupName}

Ref. Engagement Estimate
{#Opportunities}{RowNumber} {Name} {Amount:#,##0.00}{/Opportunities}

Stage subtotal   {SUM:Opportunities.Amount:#,##0.00}

{/GroupBy}
``` ## field-quote.html ```html Field station renewal {#IsDraft}
DRAFT PRICING · {QuoteNumber}
{/IsDraft}
Morrow Field Systems {QuoteNumber}
COMMERCIAL PROPOSAL

{Subject}

Prepared for {Client} · {Sponsor}

One-time investment{Currency} {OneTime:#,##0.00} Monthly support{Currency} {Monthly:#,##0.00}

Inside this proposal

Issued {Issued} · Valid through {ValidUntil}

DELIVERY

Scope of work

Review what each configuration delivers, then follow its link to inspect quantities and prices.

{#Bundles} {/Bundles}

Delivery checkpoints

When / who Milestone and acceptance check
{#Milestones}{Window}
{Owner}
{Phase}
{Check}{/Milestones}

Return to contents

CONFIGURATION SCHEDULE

Configured pricing

All prices in {Currency}. The net column includes the listed discount. Optional services are priced separately.

{#IF Bundles.totalSize = 0}

No configured bundles are included in this draft. Ask the account team for the priced configuration.

{/IF} {#Bundles}

{Name}

Component / SKU Qty List each Disc. Net
{#Components}{Sku}
{Description}
{Qty} {ListPrice:#,##0.00} {Discount}% {Net:#,##0.00}{/Components}

Bundle subtotal · {SUM:Components.Net:#,##0.00}

Monthly support · {Monthly:#,##0.00}

{#IF AddOns.totalSize > 0}
Optional service for {Name}{#AddOns}

{Description} · {Net:#,##0.00}

{/AddOns}
{/IF} {/Bundles}

Return to contents

PURCHASE REVIEW

Commercial terms

Order value

The one-time configuration totals {Currency} {OneTime:#,##0.00}. Monthly support is {Currency} {Monthly:#,##0.00}. Optional services require separate approval.

Payment schedule

Installments apply to the one-time investment.

Milestone Share Amount
{#Payments}{Due} {Share}% {Amount:#,##0.00}{/Payments}

Offer window

Reference {QuoteNumber} when approving this proposal through {ValidUntil}.

Handoff

Confirm access to the work areas with the service coordinator before scheduling installation.

Review itemized pricing · Return to contents

``` ## field-quote.json ```json { "Client": "Alder Works", "QuoteNumber": "Q-2048", "Subject": "Field station renewal", "Issued": "20 November 2026", "ValidUntil": "20 December 2026", "IsDraft": true, "Currency": "USD", "Sponsor": "Facilities Operations", "Bundles": { "totalSize": 2, "records": [ { "Key": "atlas", "Name": "Atlas station", "Use": "At each receiving bay, capture the equipment reading before dispatch.", "Components": { "totalSize": 3, "records": [ { "Sku": "AT-210", "Description": "Field station with sealed enclosure", "Qty": 2, "ListPrice": 3125, "Discount": 12, "Net": 5500.0 }, { "Sku": "AT-041", "Description": "Mount and cable harness", "Qty": 2, "ListPrice": 95, "Discount": 0, "Net": 190.0 }, { "Sku": "SV-106", "Description": "Commissioning and operator training", "Qty": 1, "ListPrice": 850, "Discount": 0, "Net": 850.0 } ] }, "AddOns": { "totalSize": 0, "records": [] }, "OneTimeNet": 6540.0, "Monthly": 60 }, { "Key": "harbor", "Name": "Harbor reserve", "Use": "Keep one station online while the site supply is being serviced.", "Components": { "totalSize": 2, "records": [ { "Sku": "HB-310", "Description": "Power cabinet with changeover relay", "Qty": 1, "ListPrice": 3750, "Discount": 8, "Net": 3450.0 }, { "Sku": "HB-014", "Description": "Reserve battery module", "Qty": 2, "ListPrice": 340, "Discount": 0, "Net": 680.0 } ] }, "AddOns": { "totalSize": 1, "records": [ { "Sku": "SV-208", "Description": "Annual on-site readiness inspection", "Qty": 1, "ListPrice": 450, "Discount": 0, "Net": 450.0 } ] }, "OneTimeNet": 4130.0, "Monthly": 60 } ] }, "OneTime": 10670.0, "Monthly": 120, "AddOnNet": 450, "Milestones": { "totalSize": 3, "records": [ { "Phase": "Site survey", "Owner": "Facilities lead", "Window": "Week 1", "Check": "Site access, power and mounting positions confirmed." }, { "Phase": "Installation", "Owner": "Field engineering", "Window": "Weeks 2–3", "Check": "Each station commissioned against the equipment list." }, { "Phase": "Acceptance", "Owner": "Operations sponsor", "Window": "Week 4", "Check": "Training and handoff checklist acknowledged." } ] }, "Payments": { "totalSize": 3, "records": [ { "Due": "At order", "Share": 30, "Amount": 3201 }, { "Due": "After commissioning", "Share": 40, "Amount": 4268 }, { "Due": "On acceptance", "Share": 30, "Amount": 3201 } ] } } ``` ## renewal-brief.html ```html Renewal review
Client services {ReviewPeriod}

RENEWAL DECISION

{Client}

{PlanName} · Renewal on {RenewalDate}

{#IF HasUsage = true} {#AtTarget}
Prepare renewal termsActive usage meets the agreed {Threshold}% threshold. Confirm scope with the sponsor before sending the renewal.
{:else}
Book an adoption reviewActive usage is below the agreed {Threshold}% threshold. Ask the sponsor which team needs help before proposing renewal terms.
{/AtTarget} {:else}
Request usage dataUsage is unavailable for this period. Check the measurement window before making a renewal recommendation.
{/IF}
Annual contractUSD {AnnualNet:#,##0} Active usage{#IF HasUsage = true}{Adoption}%{:else}Unknown{/IF} Open service cases{OpenCases}
{#IF HasUsage = true}

Where adoption differs

Active seats as a share of licensed seats, by team. The percentage is printed beside every bar.

Team Active / licensed Adoption
{#Teams}{Name} {Active} / {Licensed} {Percent}%
{/Teams}

Account adoption uses total active seats divided by total licensed seats. Last period: {PriorAdoption}%.

{/IF}

For the account owner

{#IF OpenCases > 0}

Review the {OpenCases} open service cases with the support lead. The oldest has been open for {DaysOpen} days.

{:else}

The service queue is clear. Confirm the renewal scope and decision date with the sponsor.

{/IF} ``` ## renewal-brief.json ```json { "Client": "Sable Harbor Cooperative", "ReviewPeriod": "October 2026", "RenewalDate": "31 January 2027", "AnnualNet": 86400, "DaysOpen": 18, "Threshold": 80, "HasUsage": true, "Adoption": 72, "PriorAdoption": 61, "OpenCases": 2, "PlanName": "Operations Plus", "Teams": { "totalSize": 3, "records": [ { "Name": "Dispatch", "Active": 33, "Licensed": 40, "Percent": 83 }, { "Name": "Field service", "Active": 24, "Licensed": 40, "Percent": 60 }, { "Name": "Finance", "Active": 15, "Licensed": 20, "Percent": 75 } ] }, "AtTarget": false } ``` ## service-sheet.html ```html Field service sheet

FIELD SERVICES · WORK ORDER {WorkOrder}

{Site}

Visit
{Visit}
Technician
{Technician}
Equipment
{COUNT:Equipment} units
{#Equipment}

{Name}

{Location}

{#Checks} {Task}{/Checks}

As-found reading

{*Code:qr:105}
{Code}
{/Equipment}
Desk receipt · {WorkOrder}

{Handoff}

Technician initials   Date

``` ## service-sheet.json ```json { "Site": "North pier workshop", "WorkOrder": "WO-1842", "Visit": "24 November 2026", "Technician": "Morgan Lee", "Handoff": "Return the signed paper checklist to the maintenance desk.", "Equipment": { "totalSize": 2, "records": [ { "Code": "AW-P17-201", "Name": "Circulation pump", "Location": "Bay 2 · supply manifold", "Checks": { "totalSize": 3, "records": [ { "Task": "Check motor guard and isolation label" }, { "Task": "Record cold-start pressure" }, { "Task": "Inspect the coupling for movement" } ] } }, { "Code": "AW-S08-414", "Name": "Flow sensor", "Location": "Bay 2 · return line", "Checks": { "totalSize": 3, "records": [ { "Task": "Match the serial number to the register" }, { "Task": "Record instrument reading at idle" }, { "Task": "Return the enclosure cover" } ] } } ] } } ``` # Request an agreement and open it from a Screen Flow This subscriber project lets one signed-in person prepare and open a practice agreement. The screen publishes a platform event. A second Flow creates the Portwood request and writes the result to a private receipt. The same screen interview reads that receipt and uses Salesforce’s standard **Open a Page** action to open the signer’s URL. A third Flow clears that URL after the handoff window. [See the signer’s screens](https://portwood.dev/guide#event-signing-journey) or [build it step by step in Salesforce Setup](https://portwood.dev/guide#signing-handoff-setup). This sample starts with a signed-in user. Authenticated signing for employees or portal members requires a Portwood site license. A public signing page also needs its guest user configured. [Plan licenses and request a quote](https://portwood.dev/guide#user-licenses). ## Install this optional project in a sandbox 1. Use a sandbox with Portwood installed and a configured Salesforce Site or Experience Cloud signing page. The signer and Flow execution users need the Portwood permissions and record access appropriate to their roles. The source uses Salesforce Flow API 68 and the managed `portwoodglobal` namespace. 2. From this project’s directory, deploy the sample objects, permission set and three **Draft** Flows. Substitute your sandbox alias in the command. ```bash sf project deploy start --source-dir force-app --target-org YOUR_SANDBOX ``` 3. In Portwood, create an **HTML** template using **Salesforce Record (SOQL)**. Choose **Guide Signing Receipt** as the base object and select its **Name** field (the receipt number). Upload `acceptance.html`, give the template the exact API name `Guide_Event_Acceptance`, and save and activate it. The template puts the **Customer** signing tags directly in the body. This sample signs the receipt-backed agreement. To sign an already-generated quote PDF, use Portwood’s uploaded-PDF preparation route. 4. Assign **Guide Signing Handoff** to your test signer. Grant **Run Flows** and access to **Guide · Request and open an agreement** if your org restricts flow access. Keep the receipt object private. Limit users with administrative, hierarchy or sharing-rule access to its signer-link field. The included permission set gives users read access to receipts and permission to publish this event. The background Flow writes receipts. 5. In Flow Builder, activate **Guide · Clear expired signing link**, **Guide · Prepare the agreement**, then **Guide · Request and open an agreement**. Use a supported Lightning host, for example the standard Flow component on a Lightning app page. Test with the person who will actually use the interview. Configure the org’s **Default Workflow User** if Salesforce prompts for one when you activate the scheduled cleanup. 6. Choose **Prepare agreement**, then **Open signing page**. If preparation is still pending, choose **Check again** in the same interview. The site link is for the publishing user only. After returning, use **Check signing status**. If the signer closed the signing tab, **Reopen my signing page → Check again** rechecks the private receipt and opens the same request. After signing, the Flow can report that the final file is still being saved. The finished path requires both the signed status and the protected signed File ID. ## Follow the fields | Element | Mapping | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Publish | Create `Guide_Sign_Requested__e` with `Receipt_Key__c = $Flow.InterviewGuid`. The event uses **Publish After Commit**. The next Screen commits the publication. | | Claim | Create a private `Guide_Sign_Receipt__c` with unique `Receipt_Key__c`, `Stage__c = Preparing` and `OwnerId = $Record.CreatedById`. Existing keys exit the subscriber. The database’s unique constraint also prevents a concurrent duplicate from creating a second request. A concurrent duplicate-key fault can appear in failed Flow interviews. | | Identify the signer | Read the publishing User’s name and email. Set the **DocGenSigner** role to **Customer**. Pass that one signer to **Portwood: Create Signature Request** with **Single** signing order, **Send Branded Emails = False** and one day of validity. The verification policy comes from the template and org. | | Store the outcome | On success store `Request_Id__c`, the single returned URL, its handoff expiry and **Ready**. Mark a failed or unsuccessful request **Failed** so the interview can show a recoverable explanation. Investigate that receipt before initiating another submission. | | Read the result | Filter by the interview key **and** signed-in owner. **Open a Page** receives `pageType = WebPage` and `webPageUrl = Receipt.Signer_URL__c`. The handoff screen also has a link. Rechecking reads the existing receipt. | | Clear the link | A scheduled path clears `Signer_URL__c` approximately one day after the receipt becomes ready. The interview separately checks `Link_Expires_At__c` before opening it. Keep platform-event payloads, analytics, recordings and logs free of signing URLs. | | Confirm completion | Read `portwoodglobal__DocGen_Signature_Request__c` using the stored request ID. Read the protected File through Salesforce’s normal access rules. | The retry key covers one interview. For repeat approvals across interviews, use a unique business key tied to the approved proposal and version. A business process with multiple signers also needs per-signer authorization for each handoff. The separate approval-event recipe in the guide covers those changes. [Open a Page action](https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_open_a_page.htm&language=en_US&type=5) · [Platform-event-triggered Flows](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-subscribe-flow.html) ## Guide_Open_Agreement.flow-meta.xml ```xml 68.0 Open_Signing_Page 480 934 flowruntime:openAPage lwcComponent Handoff Handoff CurrentTransaction pageType WebPage webPageUrl Receipt.Signer_URL__c flowruntime:openAPage Ready 480 789 Waiting Otherwise Prepared_Receipt and Receipt.Stage__c EqualTo Ready Receipt.Signer_URL__c IsNull false Receipt.Link_Expires_At__c GreaterThan $Flow.CurrentDateTime Open_Signing_Page Error and Receipt.Stage__c EqualTo Failed Problem Expired and Receipt.Stage__c EqualTo Ready Problem Outcome 480 1369 Pending Otherwise Done and Request.portwoodglobal__Status__c EqualTo Signed Request.portwoodglobal__Protected_Signed_Content_Document_Id__c IsNull false Complete Making_File and Request.portwoodglobal__Status__c EqualTo Signed Finalizing Declined and Request.portwoodglobal__Status__c EqualTo Declined Stopped Revoked and Request.portwoodglobal__Status__c EqualTo Cancelled Stopped Timed_Out and Request.portwoodglobal__Expires_At__c LessThan $Flow.CurrentDateTime Stopped No_Visible_Request and Request.Id IsNull true Problem Check_Again 205 1659 Request Check signing status Reopen and ReopenPage EqualTo true Receipt Guide · Request and open an agreement {!$Flow.CurrentDateTime} BuilderType LightningFlowBuilder CanvasMode AUTO_LAYOUT_CANVAS Flow Publish 480 354 Preparing Problem Receipt_Key__c $Flow.InterviewGuid Guide_Sign_Requested__e true Receipt 480 644 true Ready Problem and Receipt_Key__c EqualTo $Flow.InterviewGuid OwnerId EqualTo $User.Id true Guide_Sign_Receipt__c true Request 480 1224 true Outcome Problem and Id EqualTo Receipt.Request_Id__c true portwoodglobal__DocGen_Signature_Request__c true Confirm 480 209 false true false Publish Confirm_Instructions <p>Prepare an acceptance agreement for yourself using your signed-in identity.</p> DisplayText Prepare agreement true true Preparing 480 499 false true false Receipt Preparing_Instructions <p>The request is being prepared. Continue to look for your signing page.</p> DisplayText Open signing page true true Waiting 205 789 false true false Receipt Waiting_Instructions <p>Preparation is still running. Check the same request again in a moment.</p> DisplayText Check again true true Handoff 480 1079 false true false Request Handoff_Instructions <p>If the signing page did not open, <a href="{!Receipt.Signer_URL__c}" target="_blank">review and sign your agreement</a>. Return here to check its status.</p> DisplayText Check signing status true true Pending 205 1369 false true false Check_Again Pending_Instructions <p>Your agreement still needs a signature. Finish in the signing tab. If you closed it, select the box below and choose Check again.</p> DisplayText ReopenPage Boolean false Reopen my signing page InputField true Check again true true Finalizing 1030 1514 false true false Request Finalizing_Instructions <p>Your agreement is signed. Portwood is saving the final file. Choose Check again in a moment.</p> DisplayText Check again true true Problem 1030 789 false true false Problem_Instructions <p>Ask your administrator to check the receipt, the template and your access.</p> DisplayText true true Complete 480 1514 false true false Complete_Instructions <p>The request is signed and the protected File is ready.</p> DisplayText true true Stopped 755 1514 false true false Stopped_Instructions <p>This request is no longer available for signing. Contact the sender.</p> DisplayText true true 480 64 Confirm Draft ``` ## Guide_Prepare_Agreement.flow-meta.xml ```xml 68.0 Prepare 480 934 portwoodglobal__DocGenSignatureFlowAction apex Prepared Set_Failed templateApiName Guide_Event_Acceptance relatedRecordId Claim signerRecords People signingOrder Single sendEmails false prefillSignerEmail false expirationDays 1 RequestId signatureRequestId Links signerUrls PreparedOk success false Identify 480 789 Person.name Assign Publisher.Name Person.email Assign Publisher.Email Person.role Assign Customer People Add Person Prepare Capture_Link 205 1369 SignerLink Assign Each_Link Each_Link New_Receipt 480 354 Claim Otherwise Seen and Prior.Id IsNull false Prepared 480 1079 Set_Failed Otherwise Have_Request and PreparedOk EqualTo true RequestId IsNull false Each_Link Has_Link 480 1514 Set_Failed Otherwise Link_Ready and SignerLink IsNull false Set_Ready Expires DateTime NOW() + 1 Guide · Prepare the agreement {!$Flow.CurrentDateTime} BuilderType LightningFlowBuilder CanvasMode AUTO_LAYOUT_CANVAS AutoLaunchedFlow Each_Link 480 1224 Links Asc Capture_Link Has_Link Claim 480 499 Publisher OwnerId $Record.CreatedById Receipt_Key__c $Record.Receipt_Key__c Stage__c Preparing Guide_Sign_Receipt__c true Prior 480 209 false New_Receipt and Receipt_Key__c EqualTo $Record.Receipt_Key__c true Guide_Sign_Receipt__c true Publisher 480 644 false Identify Set_Failed and Id EqualTo $Record.CreatedById true User true Set_Ready 480 1659 and Id EqualTo Claim Stage__c Ready Request_Id__c RequestId Signer_URL__c SignerLink Link_Expires_At__c Expires Guide_Sign_Receipt__c Set_Failed 1030 1224 and Id EqualTo Claim Stage__c Failed Request_Id__c RequestId Guide_Sign_Receipt__c 480 64 Prior Guide_Sign_Requested__e PlatformEvent Draft Person portwoodglobal__DocGenSigner Apex false false false People portwoodglobal__DocGenSigner Apex true false false RequestId String false false false Links String true false false SignerLink String false false false PreparedOk Boolean false false false ``` ## Guide_Clear_Handoff_Link.flow-meta.xml ```xml 68.0 Guide · Clear expired signing link {!$Flow.CurrentDateTime} BuilderType LightningFlowBuilder CanvasMode AUTO_LAYOUT_CANVAS AutoLaunchedFlow Clear_Link 480 209 and Id EqualTo $Record.Id Signer_URL__c ClearedURL Guide_Sign_Receipt__c 480 64 true and Stage__c EqualTo Ready Guide_Sign_Receipt__c CreateAndUpdate Expired Clear_Link 1 Days RecordTriggerEvent RecordAfterSave Draft ClearedURL String false false false ```