DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
document generation

Using Conditions and Loops in Code-Based PDF Templates

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use conditions to include or omit whole pieces of document content, and loops to repeat a template fragment for each item in an array. For an invoice, that usually means putting a condition around the entire discount row and looping over the line-item rows. The exact syntax depends on the template engine; the reliable approach is to prepare predictable data, make empty and zero-value behavior explicit, and inspect real PDF output with representative fixtures.

How conditions and loops work in a PDF template

A code-based PDF template separates reusable layout from runtime data. The template defines the document’s structure and presentation; the input data supplies values such as customer details, invoice items and discounts. A renderer evaluates the template’s tags or placeholders and produces the PDF.

The authoring format and the templating language are related but distinct choices. PDFMonkey documents HTML/CSS templates with Liquid tags; PDFBolt documents HTML with Handlebars placeholders; Carbone combines HTML/CSS with JSON data; Apryse uses an Office document with JSON replacement data. iText DITO provides a visual, low-code approach to data binding and conditional logic. Do not assume that syntax or behavior from one engine will work in another.

  • A condition controls whether a block is emitted, or which block is chosen.
  • A loop repeats a block for members of a list, such as one table row per invoice item.

These constructs decide what content appears; CSS and the renderer still determine layout, page breaks and typography. A condition can remove content and allow what follows to reflow, but it cannot guarantee that a table or section will paginate exactly as intended.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Scrivar PDF Pro - Organize, Edit, Compress, Convert, Merge, eSign, OCR & 30+ tools | Lifetime License
  • EVERY PDF TOOL UNLOCKED - 30+ tools in one app: edit text and images, convert, merge, split, compress, sign, OCR, redact, watermark, batch process, and more. No feature gates, no upsells, nothing held back.
  • PAY ONCE, OWN FOREVER — A one-time purchase, not a subscription. Other apps runs $240/year — Scrivar is yours for life, with free updates included.
  • UNLIMITED eSIGN, BUILT IN — Send contracts and forms for signature and track every step. Recipients sign in their browser with no account or app needed. Replace DocuSign and save hundreds a year.
  • PC, MAC, AND WEB — Install on any Win 10/11 PC or macOS 11+ Mac (Intel or Apple Silicon), or work in your browser at scrivar.com. Same tools, same account, everywhere you work.
  • OCR + FULL OFFICE CONVERSION — Turn scanned documents into searchable, selectable text, and convert PDFs to and from Word, Excel, and PowerPoint with formatting kept intact.

Write conditions around complete semantic blocks

Put a condition around the whole unit that should disappear—not only its value. If a discount is absent, for example, omit its label and its amount together. Leaving either behind can produce an empty label, a blank table row or confusing whitespace.

In iText DITO, the documented conditional-selection behavior is that when a condition is false, the selection is omitted and the rest of the document reflows. Its examples include omitting an invoice discount row unless the discount is greater than zero. Adobe’s Document Generation API documents comparison operators =, !=, >=, >, <= and < in conditional expressions. These examples illustrate why a deliberate comparison is often clearer than relying on an engine’s implicit truthiness rules.

Decide what “present” means for each field

Before writing a condition, define how the document should treat each relevant value:

  • Null: Is the value unknown, or should the entire section be omitted?
  • Empty string: Should it behave like missing data, or should an intentionally blank field remain visible?
  • Zero: A zero price, quantity or discount may be meaningful. A generic “value is truthy” check can accidentally hide it.
  • False: A boolean false may mean “do not show this feature,” but it is not the same as a missing value.

Use the engine’s documented syntax to express the business rule explicitly. The comparison operators and typed text, numeric and boolean conditions documented for Adobe’s API and iText DITO are useful models, but they are not interchangeable syntax. Confirm how your selected engine treats nulls, empty values and type conversion instead of assuming behavior based on another language.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Corel WordPerfect Office Home & Student 2021 | Office Suite of Word Processor, Spreadsheets & Presentation Software [PC Download]
  • What’s Included: Digital delivery with instant access to WordPerfect; serial key available in your Software Library. For Windows PC only.
  • Essential Office Suite: WordPerfect for word processing, Quattro Pro for building spreadsheets, Presentations for creating slideshows, and WordPerfect Lightning for digital note‑taking
  • Seamless File Compatibility: Open, edit, and share more than 60 familiar file types—including Microsoft Office formats (Word DOC/DOCX, Excel XLS/XLSX, and PowerPoint PPT/PPTX)
  • Creative Content: Includes 900+ TrueType fonts, 10,000+ clip art images, 300+ templates, 175+ digital photos, WordPerfect Address Book, Presentations Graphics (bitmap editor and drawing application), and WordPerfect XML Project Designer
  • Reveal Codes: Turn on Reveal Codes to edit the codes and adjust formatting and structure

Example: conditionally include a discount row

Here is the shape of the logic in pseudocode; use the conditional tags documented by your chosen engine:

IF discount_amount is greater than 0:
  render one table row containing "Discount" and discount_display

The condition wraps the entire row, so no label or cell remains when the discount does not qualify. The application should decide whether the comparison uses a numeric value and supply a display-ready amount separately. That keeps currency formatting out of the condition and reduces ambiguity around strings such as "0".

Use loops for arrays of repeating content

A loop repeats a fragment once for each member of a list. Choose the smallest repeating unit that owns the data: usually a table row for invoice items or a list item for report entries. A loop around an entire page or table is appropriate only when that larger unit genuinely repeats.

PDFBolt’s Handlebars examples use {{#each items}} ... {{/each}} to repeat content. PDFMonkey lists Liquid’s for and tablerow tags. Apryse states that its Office-template framework supports list loops and dynamic item renumbering. Those examples establish the pattern, not a universal syntax: check the relevant engine documentation for context variables, escaping and loop metadata.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
  • Create a mix using audio, music and voice tracks and recordings.
  • Customize your tracks with amazing effects and helpful editing tools.
  • Use tools like the Beat Maker and Midi Creator.
  • Work efficiently by using Bookmarks and tools like Effect Chain, which allow you to apply multiple effects at a time
  • Use one of the many other NCH multimedia applications that are integrated with MixPad.

Example: repeat invoice rows

For a Handlebars-style template, a simplified table body could look like this:

<tbody>
  {{#each items}}
    <tr>
      <td>{{description}}</td>
      <td>{{quantity_display}}</td>
      <td>{{unit_price_display}}</td>
      <td>{{line_total_display}}</td>
    </tr>
  {{/each}}
</tbody>

This is a template fragment, not a complete service request or a promise that every Handlebars-based renderer accepts identical markup. Supply an items array with consistently named fields and use the syntax supported by the renderer that processes the template.

Prepare data before rendering

Normalize the input before it reaches the template. Give arrays a stable order, keep numeric values numeric for comparisons, and calculate display fields such as formatted totals in the application when that keeps the template simpler. Avoid embedding business calculations or type conversions in a long chain of template expressions. A template should make the document rule easy to inspect; data preparation should make the rule’s inputs dependable.

Decide explicitly what an empty array means. If an invoice with no items is invalid, reject it before rendering. If a report may have no results, either omit the table as a whole or show a clear “No items” message. Do not render an empty table with only headers unless that is the intended document design. The exact empty-list syntax varies by engine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a template approach that fits the people and document

Approach What the documented option provides Consider it when
HTML/CSS with Liquid PDFMonkey documents HTML/CSS templates using Liquid tags, including for and tablerow. Your team owns HTML/CSS and wants familiar template control tags.
HTML with Handlebars PDFBolt documents HTML placeholders and examples of conditions and each loops. You want to author markup and express repeating data with Handlebars-style blocks.
HTML/CSS with JSON Carbone says it renders HTML/CSS through Chromium, injects JSON, loops over arrays and applies conditions in one API call. Your team is web-oriented and generates data-driven documents such as invoices or reports.
Office document with JSON Apryse accepts an Office document and JSON replacement data; its documented capabilities include loops, conditionals, images and tables. Document authors prefer working in Word-compatible editors.
Visual, low-code mapping iText DITO documents data binding, conditional logic and filtered loops, including typed text, numeric and boolean conditions. Business users need a visual editor while developers need control over document generation.

Compare more than the syntax. Check expression capabilities, how data is validated, pagination and reflow behavior, image and font support, preview and versioning, deployment, observability, licensing and data residency. There is no reliable cross-vendor speed, defect-rate or total-cost benchmark established by the documented material cited here, so evaluate those factors with your own representative documents rather than inferring a winner from feature lists.

Build and validate a template in a production workflow

  1. Define the input contract. Write a JSON schema or equivalent for the data your renderer accepts. Specify required fields, types, allowed nulls and whether arrays may be empty.
  2. Create representative fixtures. Include ordinary data, empty arrays, nulls, zero values, false booleans, long text and the largest realistic document. Add fixtures for conditional combinations that change which sections appear.
  3. Implement the smallest useful blocks. Put each condition around the complete content unit it controls, and loop at the row or item level. Prefer explicit rules over expressions whose meaning depends on implicit coercion.
  4. Validate template and data before rendering. Catch malformed template syntax and unexpected data shapes early. PDFBolt documents a draft → validate → preview → publish → generate lifecycle; use the corresponding validation steps available in your selected product.
  5. Inspect a real PDF preview. Check page breaks, repeated table headers, orphaned headings, font fallback, links, long strings and whether conditional omissions leave unwanted gaps. PDFBolt distinguishes an HTML preview from a real PDF preview made with its conversion renderer.
  6. Publish a version and preserve a baseline. Keep the template version, fixture data and resulting PDF together so a later change can be compared against a known output.

A source review can confirm that tags appear balanced; it cannot prove that rendered pagination is acceptable. Treat the generated PDF—not just the template or an HTML preview—as the artifact to approve.

Fix blank rows, missing content and pagination defects

Symptom Likely cause What to check
A blank row or label remains when a field is absent. The condition wraps the value but not the full row or block, or the check treats empty and null differently than expected. Move the condition around the whole semantic unit; test null and empty-string fixtures separately.
A valid zero amount disappears. A truthiness check treats numeric zero as false, or the input arrived as an unexpected type. Use an explicit numeric comparison and validate the input type before rendering.
Only one item appears, or the loop fails. The input is not an array, the array key differs from the template, or the loop syntax belongs to another engine. Inspect the actual data shape, match the expected property name, and verify the selected renderer’s loop syntax.
An empty table appears with no useful content. The loop correctly has no members, but the template has no empty-list design. Choose an explicit policy: omit the table, show an empty-state message, or reject the input if an empty list is invalid.
Rows or sections move unexpectedly between pages. Conditional omission changed the document flow, or the rendered table is longer than the preview fixture. Inspect a real PDF with worst-case content; check renderer pagination and table-header behavior rather than relying on source layout alone.
Text, currency or totals are inconsistent. Formatting or calculations are being mixed into template logic, or values have inconsistent types. Normalize numeric data and provide consistent display fields before rendering.

When a defect is intermittent, save the exact input fixture and generated PDF. Re-rendering the same fixture against a changed template can distinguish a data-shape problem from a layout regression.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is not a PDF-template engine: it does not replace a Liquid, Handlebars, JSON or Office template renderer. It can be useful for a neighboring QA task—capturing a web-based preview of a generated document or its surrounding page—without configuring a browser yourself. It is a website screenshot API and MCP server for developers, made by Yorker Media. One GET request returns a PNG, JPEG or WebP screenshot, or a PDF. See the ScreenshotNeo site and API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Replace the target URL with a page you can access and replace YOUR_API_KEY with your key. Cookie banners, newsletter popups and chat widgets are removed before the shot; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies page verdict and billing status in headers. An MCP server exposes take_screenshot, get_page_info and capture_pdf to AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up free for 1,000 screenshots a month—no card required.

Cost, performance and reliability decisions

Template documentation describes features and workflows, not a common performance benchmark. Rendering time, reliability and cost depend on the chosen renderer, document complexity, data size, fonts, images and deployment model. Test realistic page counts, long tables, large images and concurrent jobs under your own expected conditions before selecting production limits. The available documentation does not establish a cross-vendor benchmark for speed, defect rate or total cost.

For reliability, validate data before a render, preserve the input associated with each failed output, and distinguish template errors from renderer or layout issues in logs. Retain versioned templates and representative generated PDFs so changes to conditions, loops or styling can be reviewed as document changes rather than treated as invisible code edits.

Frequently Asked Questions

Can a template loop calculate invoice totals?

It is usually clearer to calculate and validate totals in application code, then pass the resulting numeric and display values into the template. Keep the loop focused on repeating rows.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I copy a Liquid condition into a Handlebars template?

No. Liquid and Handlebars are separate template syntaxes. Use the tags and expression rules documented for the renderer that evaluates the template.

Does a correct HTML preview guarantee the generated PDF will paginate correctly?

No. Inspect the actual PDF output, since the conversion renderer and page layout determine final pagination.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.