PDF Placeholder Gate

Fix: Placeholder Tags Appear in Final PDF Instead of Rendered Values

Separate replacement failures from export-order mistakes, inspect every Word story range, and block PDF creation until no unresolved {{...}} tags remain.

Literal tags detected
All Word stories
Export blocked safely
DOCX + PDF review
PDF export does not resolve custom text tags. It captures the Word document supplied to the export step. Validate the exact document, output path, and remaining placeholders before release.

Quick answer: fix the Word document before exporting it

A PDF exporter does not know that {{ClientName}} is supposed to become a customer name. If the literal tag is still present in the Word document passed to export, the PDF correctly reproduces that literal text. Complete replacement first, clear optional tags explicitly, scan every Word story range, and export only after the scan returns zero unresolved items.

Tags remain in DOCX and PDF

The replacement stage failed or skipped a location. Repair the mapping before investigating PDF settings.

DOCX is correct, old PDF is not

The workflow may be opening a previous PDF, exporting another document, or reusing an existing output name.

Only headers show tags

The code probably searched Document.Content but never scanned header and footer stories.

Only text boxes show tags

The replacement or validation logic did not traverse text-frame story ranges.

Core rule

The export step must be downstream of replacement, optional-value handling, field updates, placeholder validation, and DOCX save. A PDF setting cannot compensate for a Word document that still contains template syntax.

Diagnose the failure before changing the template

Use the exact generated Word file and PDF from one failed record. Similar-looking test files and reused output names hide the real stage that failed.

One tag remains everywhere

Likely cause: the source key does not match the template spelling, case policy, or braces. Check: compare the literal tag with the configured field name.

Optional tags remain

Likely cause: blank values were skipped instead of replacing their tags with an empty string or an approved fallback.

Only one section fails

Likely cause: replacement covered the main text but not a first-page header, footer, linked text box, footnote, or endnote.

Some tags use different braces

Likely cause: the template mixes {{Name}}, <<Name>>, content controls, and Word fields. Pick one supported contract instead of scanning every symbol.

The PDF timestamp is old

Likely cause: overwrite protection or file naming sent the new export elsewhere. Confirm the full final path and modified time.

The PDF was exported too early

Likely cause: ExportAsFixedFormat ran before replacement, field updates, or the final save completed.

Use a fail-closed Word-to-PDF order

Treat PDF creation as the final controlled step, not as an automatic side effect of opening a template.

1. Create a fresh document

Start from the approved Word template for the current record. Do not edit and reuse the previous output.

2. Replace required tags

Every required source value must map to an exact literal tag in the intended document stories.

3. Resolve optional tags

Replace blank optional values with an empty string or approved wording. Never leave the tag because the value is blank.

4. Update Word fields

Update fields only after literal tag replacement, and stop if a required field cannot update.

5. Scan and save DOCX

Search all story ranges for unresolved delimiters, save the verified Word file, and scan it again.

6. Export and commit PDF

Create the PDF in a unique temporary folder and move it to the final name only after a nonempty file exists.

Define one literal-tag contract

This article uses double braces for plain text placeholders. Word fields, Mail Merge fields, content controls, bookmarks, and DocxForge image tags require their own handling and should not be treated as interchangeable.

Example text tags

{{ClientName}}, {{InvoiceDateDisplay}}, {{TotalAmountDisplay}}, and {{Notes}}. Use document-ready display strings for dates, currencies, identifiers, and percentages when the final wording must be preserved.

Exact names

Choose one case policy and keep the same spelling in the source, mapping, template, and validation report.

Required versus optional

Reject missing required values. Clear optional tags explicitly rather than omitting the replacement call.

Use one delimiter system

Do not combine double braces with angle brackets or square brackets unless every system has a documented processor. If the failure begins during Excel-to-Word replacement, repair the source mapping and replacement stage first. This article focuses on preventing an unresolved Word document from becoming a final PDF.

Run one manual export gate first

Confirm the logic on a disposable document before using the macro in a batch.

Search for the opening delimiter

Search the generated Word file for {{. Repeat the search inside headers, footers, and visible text boxes.

Test a required missing value

Remove one source value deliberately and confirm the process stops instead of exporting a PDF.

Test an optional blank value

Confirm the tag disappears cleanly and does not leave braces, double spaces, or an empty paragraph.

Confirm the exact output file

Check the full PDF path, filename, and modified time so an older export is not mistaken for the new result.

Do not approve from DOCX alone

After the gate passes, open the newly created PDF and verify the text, pagination, headers, footers, and filename. The VBA verifies Word state and successful file creation; it does not parse the finished PDF text.

Free Word VBA helper: block PDF export when tags remain

Run this from the generated Word document after the upstream replacement step. It updates fields, scans every available Word story range for paired or unmatched double braces, saves and rescans the DOCX, creates a temporary PDF, and refuses to replace an existing final file.

Scope

The helper validates literal {{...}} text. It does not populate missing values, authenticate business data, inspect embedded objects, or prove that the PDF visually matches the approved template. Use it as an export gate, not as the complete generation system.

Option Explicit

Private Const OUTPUT_FOLDER_NAME As String = "PDF"
Private Const PLACEHOLDER_OPEN As String = "{{"
Private Const PLACEHOLDER_CLOSE As String = "}}"
Private Const FILE_ATTRIBUTES As Long = 7
Private Const FOLDER_ATTRIBUTES As Long = 22
Private Const MAX_REPORTED_FINDINGS As Long = 20

Public Sub ValidateAndExportActiveDocumentToPdf()
    Dim targetDoc As Document
    Dim outputFolder As String
    Dim runFolder As String
    Dim tempPdfPath As String
    Dim finalPdfPath As String
    Dim baseName As String
    Dim unresolvedReport As String
    Dim unresolvedCount As Long
    Dim oldDisplayAlerts As Long
    Dim oldScreenUpdating As Boolean
    Dim currentStep As String
    Dim errorNumber As Long
    Dim errorDescription As String

    On Error GoTo CleanFail

    Set targetDoc = ActiveDocument
    oldDisplayAlerts = Application.DisplayAlerts
    oldScreenUpdating = Application.ScreenUpdating

    Application.DisplayAlerts = wdAlertsNone
    Application.ScreenUpdating = False

    currentStep = "checking the active Word document"
    If Len(targetDoc.Path) = 0 Then
        Err.Raise vbObjectError + 3200, , _
            "Save the generated Word document before running this export gate."
    End If
    If targetDoc.ReadOnly Then
        Err.Raise vbObjectError + 3201, , _
            "The active document is read-only. Save an editable review copy first."
    End If
    If targetDoc.ProtectionType <> wdNoProtection Then
        Err.Raise vbObjectError + 3202, , _
            "The active document is protected. Review the approved process " & _
            "before changing fields or exporting."
    End If

    currentStep = "updating Word fields in every story range"
    UpdateFieldsEverywhere targetDoc

    currentStep = "checking for unresolved placeholder tags"
    unresolvedCount = CollectUnresolvedPlaceholders( _
        targetDoc, unresolvedReport)

    If unresolvedCount > 0 Then
        If unresolvedCount > MAX_REPORTED_FINDINGS Then
            unresolvedReport = unresolvedReport & vbCrLf & _
                "Additional unresolved items were omitted from this message."
        End If

        Err.Raise vbObjectError + 3203, , _
            CStr(unresolvedCount) & _
            " unresolved placeholder item(s) remain:" & vbCrLf & _
            unresolvedReport
    End If

    currentStep = "saving the verified Word document"
    targetDoc.Save

    currentStep = "rechecking the saved Word document"
    unresolvedReport = vbNullString
    unresolvedCount = CollectUnresolvedPlaceholders( _
        targetDoc, unresolvedReport)
    If unresolvedCount > 0 Then
        Err.Raise vbObjectError + 3204, , _
            "Placeholder text appeared after saving. PDF export was blocked."
    End If

    outputFolder = JoinPath(targetDoc.Path, OUTPUT_FOLDER_NAME)
    EnsureFolderExists outputFolder

    baseName = GetBaseName(targetDoc.Name)
    If Len(baseName) = 0 Then
        Err.Raise vbObjectError + 3205, , _
            "Could not derive a PDF name from the active document."
    End If

    finalPdfPath = JoinPath(outputFolder, baseName & ".pdf")
    If FileExists(finalPdfPath) Then
        Err.Raise vbObjectError + 3206, , _
            "Final PDF already exists: " & finalPdfPath
    End If

    currentStep = "creating the run-specific temporary folder"
    runFolder = CreateRunFolder(outputFolder)
    tempPdfPath = JoinPath(runFolder, baseName & ".pdf")

    currentStep = "exporting the verified document to temporary PDF"
    targetDoc.ExportAsFixedFormat _
        OutputFileName:=tempPdfPath, _
        ExportFormat:=wdExportFormatPDF, _
        OpenAfterExport:=False, _
        OptimizeFor:=wdExportOptimizeForPrint, _
        Range:=wdExportAllDocument, _
        Item:=wdExportDocumentContent, _
        IncludeDocProps:=True, _
        KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateHeadingBookmarks, _
        DocStructureTags:=True, _
        BitmapMissingFonts:=True, _
        UseISO19005_1:=False

    If Not FileExists(tempPdfPath) Then
        Err.Raise vbObjectError + 3207, , _
            "Word did not create the temporary PDF."
    End If
    If FileLen(tempPdfPath) <= 0 Then
        Err.Raise vbObjectError + 3208, , _
            "Word created an empty temporary PDF."
    End If

    currentStep = "committing the final PDF"
    If FileExists(finalPdfPath) Then
        Err.Raise vbObjectError + 3209, , _
            "A final PDF appeared during export: " & finalPdfPath
    End If

    Name tempPdfPath As finalPdfPath
    If Not FileExists(finalPdfPath) Or FileLen(finalPdfPath) <= 0 Then
        Err.Raise vbObjectError + 3212, , _
            "The final PDF could not be verified after the move."
    End If
    CleanupRunFolder runFolder
    runFolder = vbNullString

    Application.DisplayAlerts = oldDisplayAlerts
    Application.ScreenUpdating = oldScreenUpdating

    MsgBox "PDF created after the placeholder gate passed:" & vbCrLf & _
        finalPdfPath & vbCrLf & vbCrLf & _
        "Open and review the PDF before release.", _
        vbInformation, "PDF export complete"
    Exit Sub

CleanFail:
    errorNumber = Err.Number
    errorDescription = Err.Description

    On Error Resume Next
    If Len(runFolder) > 0 Then CleanupRunFolder runFolder
    Application.DisplayAlerts = oldDisplayAlerts
    Application.ScreenUpdating = oldScreenUpdating
    On Error GoTo 0

    MsgBox "PDF export stopped while " & currentStep & "." & vbCrLf & _
        "Error " & errorNumber & ": " & errorDescription & vbCrLf & _
        "Correct the Word document and run the gate again.", _
        vbCritical, "PDF export blocked"
End Sub

Private Sub UpdateFieldsEverywhere(ByVal targetDoc As Document)
    Dim firstStory As Range
    Dim currentStory As Range
    Dim fieldItem As Field
    Dim fieldIndex As Long

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory

        Do While Not currentStory Is Nothing
            For fieldIndex = 1 To currentStory.Fields.Count
                Set fieldItem = currentStory.Fields(fieldIndex)
                If Not fieldItem.Update Then
                    Err.Raise vbObjectError + 3210, , _
                        "Word could not update a field in " & _
                        StoryTypeLabel(currentStory.StoryType) & "."
                End If
            Next fieldIndex

            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory
End Sub

Private Function CollectUnresolvedPlaceholders( _
    ByVal targetDoc As Document, _
    ByRef reportText As String) As Long

    Dim firstStory As Range
    Dim currentStory As Range
    Dim storyNumber As Long
    Dim findingCount As Long

    reportText = vbNullString

    For Each firstStory In targetDoc.StoryRanges
        Set currentStory = firstStory
        storyNumber = 0

        Do While Not currentStory Is Nothing
            storyNumber = storyNumber + 1
            ScanTextForPlaceholders _
                currentStory.Text, _
                StoryTypeLabel(currentStory.StoryType) & _
                    " #" & storyNumber, _
                findingCount, _
                reportText

            Set currentStory = currentStory.NextStoryRange
        Loop
    Next firstStory

    CollectUnresolvedPlaceholders = findingCount
End Function

Private Sub ScanTextForPlaceholders( _
    ByVal sourceText As String, _
    ByVal locationLabel As String, _
    ByRef findingCount As Long, _
    ByRef reportText As String)

    Dim searchPosition As Long
    Dim openPosition As Long
    Dim closePosition As Long
    Dim tokenText As String

    searchPosition = 1

    Do
        openPosition = InStr( _
            searchPosition, sourceText, PLACEHOLDER_OPEN, vbBinaryCompare)
        closePosition = InStr( _
            searchPosition, sourceText, PLACEHOLDER_CLOSE, vbBinaryCompare)

        If openPosition = 0 And closePosition = 0 Then Exit Do

        If closePosition > 0 And _
           (openPosition = 0 Or closePosition < openPosition) Then
            findingCount = findingCount + 1
            AppendFinding reportText, findingCount, _
                locationLabel, "unmatched }}"
            searchPosition = closePosition + Len(PLACEHOLDER_CLOSE)
        Else
            closePosition = InStr( _
                openPosition + Len(PLACEHOLDER_OPEN), _
                sourceText, PLACEHOLDER_CLOSE, vbBinaryCompare)

            findingCount = findingCount + 1
            If closePosition = 0 Then
                tokenText = Mid$(sourceText, openPosition, 100)
                AppendFinding reportText, findingCount, _
                    locationLabel, _
                    CleanSnippet(tokenText) & " [missing }}]"
                Exit Do
            Else
                tokenText = Mid$( _
                    sourceText, _
                    openPosition, _
                    closePosition + Len(PLACEHOLDER_CLOSE) - openPosition)
                AppendFinding reportText, findingCount, _
                    locationLabel, CleanSnippet(tokenText)
                searchPosition = closePosition + Len(PLACEHOLDER_CLOSE)
            End If
        End If
    Loop
End Sub

Private Sub AppendFinding( _
    ByRef reportText As String, _
    ByVal findingNumber As Long, _
    ByVal locationLabel As String, _
    ByVal tokenText As String)

    If findingNumber > MAX_REPORTED_FINDINGS Then Exit Sub

    If Len(reportText) > 0 Then reportText = reportText & vbCrLf
    reportText = reportText & CStr(findingNumber) & ". " & _
        locationLabel & ": " & tokenText
End Sub

Private Function CleanSnippet(ByVal valueText As String) As String
    valueText = Replace(valueText, vbCr, " ")
    valueText = Replace(valueText, vbLf, " ")
    valueText = Replace(valueText, vbTab, " ")
    valueText = Replace(valueText, Chr$(7), " ")
    valueText = Trim$(valueText)

    If Len(valueText) > 120 Then
        valueText = Left$(valueText, 117) & "..."
    End If

    CleanSnippet = valueText
End Function

Private Function StoryTypeLabel(ByVal storyType As Long) As String
    Select Case storyType
        Case wdMainTextStory
            StoryTypeLabel = "main text"
        Case wdFootnotesStory
            StoryTypeLabel = "footnotes"
        Case wdEndnotesStory
            StoryTypeLabel = "endnotes"
        Case wdCommentsStory
            StoryTypeLabel = "comments"
        Case wdTextFrameStory
            StoryTypeLabel = "text frame"
        Case wdPrimaryHeaderStory
            StoryTypeLabel = "primary header"
        Case wdFirstPageHeaderStory
            StoryTypeLabel = "first-page header"
        Case wdEvenPagesHeaderStory
            StoryTypeLabel = "even-page header"
        Case wdPrimaryFooterStory
            StoryTypeLabel = "primary footer"
        Case wdFirstPageFooterStory
            StoryTypeLabel = "first-page footer"
        Case wdEvenPagesFooterStory
            StoryTypeLabel = "even-page footer"
        Case Else
            StoryTypeLabel = "story type " & CStr(storyType)
    End Select
End Function

Private Function GetBaseName(ByVal fileName As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetBaseName = fso.GetBaseName(fileName)
End Function

Private Sub EnsureFolderExists(ByVal folderPath As String)
    If Len(Dir$(folderPath, FOLDER_ATTRIBUTES)) = 0 Then
        MkDir folderPath
    End If
End Sub

Private Function CreateRunFolder(ByVal outputFolder As String) As String
    Dim candidate As String
    Dim attempt As Long

    Randomize

    For attempt = 1 To 50
        candidate = JoinPath( _
            outputFolder, _
            "_run_" & Format$(Now, "yyyymmdd_hhnnss") & "_" & _
            Format$(Int(Rnd() * 1000000), "000000"))

        If Len(Dir$(candidate, FOLDER_ATTRIBUTES)) = 0 Then
            MkDir candidate
            CreateRunFolder = candidate
            Exit Function
        End If
    Next attempt

    Err.Raise vbObjectError + 3211, , _
        "Could not create a unique temporary run folder."
End Function

Private Sub CleanupRunFolder(ByVal runFolder As String)
    Dim fso As Object

    If Len(runFolder) = 0 Then Exit Sub

    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FolderExists(runFolder) Then
        fso.DeleteFolder runFolder, True
    End If
End Sub

Private Function FileExists(ByVal filePath As String) As Boolean
    FileExists = (Len(Dir$(filePath, FILE_ATTRIBUTES)) > 0)
End Function

Private Function JoinPath( _
    ByVal folderPath As String, _
    ByVal childName As String) As String

    If Right$(folderPath, 1) = "\" Then
        JoinPath = folderPath & childName
    Else
        JoinPath = folderPath & "\" & childName
    End If
End Function

The macro uses Word’s Document.StoryRanges and NextStoryRange to reach repeated headers, footers, and linked text frames. It checks Field.Update, saves through Document.Save, and creates the PDF with ExportAsFixedFormat.

Saved editable document required

The gate rejects unsaved, read-only, and protected documents instead of forcing changes through.

All available stories scanned

Main text, headers, footers, footnotes, endnotes, comments, and linked text-frame stories are checked.

Unmatched braces reported

A lone opening or closing delimiter is treated as unresolved template syntax.

Report is bounded

The macro counts every finding but lists only the first 20 so one broken batch does not create an unusable dialog.

Temporary PDF first

Word exports into a unique run folder and verifies that the file exists and is nonempty.

No ordinary overwrite

The final path is checked twice, and the move fails if another PDF appears during export.

Known boundary

Story-range scanning does not guarantee inspection of text inside every grouped drawing, SmartArt object, chart, embedded file, or third-party object. Keep business placeholders in supported Word text stories and include those objects in manual review.

Use the DocxForge Pro module that matches the document set

A repeatable generator can keep data mapping and output creation in one controlled local workflow. The template tags still need exact names, supported syntax, reviewed values, and a real pilot.

Factory: many rows

Use many Excel rows with one standard Word template and create a separate output for each selected row.

Factory PDF fit

Use it when the same tag contract and layout repeat across a batch of standardized documents.

Contractor: one case

Keep one case’s data together and create several different documents from different Word templates.

Contractor PDF fit

Use it when the same case values must populate a coordinated pack with different tag sets and layouts.

Product boundary

DocxForge Pro cannot infer the intended value of an unknown or misspelled tag. Keep the source-to-template mapping explicit, resolve optional fields deliberately, and review both generated DOCX and PDF output.

Compare the two local generation workflows

The screenshots are grouped by module so a row-based batch is not confused with a multi-document case pack.

Factory: many rows, one standard template

DocxForge Pro Factory Excel data screen
Review the row values that feed the standard tag contract.
DocxForge Pro Factory documents screen
Create and review one standardized output per selected row.

Contractor: one case, several different documents

DocxForge Pro Contractor case data screen
Keep reviewed values for one case in one controlled workspace.
DocxForge Pro Contractor documents screen
Apply those values across different documents and Word templates.
DocxForge Pro pricing

7 days free, then $38 every 3 months • 14-day refund after purchase • Microsoft Word Desktop required • local processing.

Run a six-document placeholder pilot

Use failures that prove each part of the gate works before adding it to a larger generation process.

All required values present

Confirm a clean document passes and produces a new PDF in the expected folder.

Missing required value

Leave one literal tag and confirm the macro reports its story and blocks export.

Optional value blank

Confirm the upstream replacement clears the tag before the gate runs.

Header placeholder

Place a disposable tag in a header and confirm story-range scanning finds it.

Text-box placeholder

Place a disposable tag in an ordinary Word text box and confirm it is reported.

Existing final PDF

Create a conflicting PDF and confirm the helper refuses to replace it.

Pilot exit criteria

Approve only after the clean case passes, every intentional failure blocks export, the final path is correct, and a reviewer opens both the verified DOCX and newly created PDF.

Frequently asked questions

Why does the PDF show {{ClientName}} instead of the client name?

The literal tag was still present in the Word document supplied to the PDF export step. Correct the source mapping or replacement order, clear optional tags explicitly, and block export until a full-document scan returns zero unresolved items.

Can PDF export settings render custom placeholder tags?

No. ExportAsFixedFormat saves the current Word document as PDF; it does not know the business meaning of custom double-brace text. Replacement must happen before export.

Why do tags remain only in headers, footers, or text boxes?

Code that searches only Document.Content covers the main story. Headers, footers, and linked text frames use other story ranges and need explicit replacement and validation.

What should happen when an optional source value is blank?

The workflow should replace the optional tag with an empty string or approved fallback text. Skipping the replacement call leaves visible template syntax in the document.

Does the VBA helper prove that the PDF is visually correct?

No. It proves that the supported Word story ranges contain no detected double-brace placeholders and that Word created a nonempty PDF. A reviewer must still inspect text, layout, pagination, images, and the final filename.

Which DocxForge Pro module fits placeholder-driven PDFs?

Factory fits many Excel rows and one standard Word template. Contractor fits one case that creates several different documents from different templates. Both still require exact tags, reviewed source values, and a real output pilot.

Stop unresolved tags before they become final PDFs

Keep replacement, validation, DOCX saving, and PDF export in one explicit order. Use the DocxForge Pro module that matches the document set, and inspect the real output before release.

7 days free, then $38 every 3 months • 14-day refund after purchase • Microsoft Word Desktop required • local processing.