Attribute VB_Name = "B07_ExportPDFMacro_en"
' ============================================================
' B07_ExportPDFMacro_en.bas
' B07_导出PDF宏_en.bas
'
' Companion tutorial: B7 *Mail Merge at Scale with AI* (English)
' Purpose: Split the merged document (one letter per section)
'          into individual PDF files.
' 配套教程：B7《用 AI + 邮件合并批量生成通知》（英文版）
'
' Install: In Word press Alt+F11, right-click the project →
'          Import File, pick this .bas.
' 安装方法：Word 里按 Alt+F11 打开 VBA 编辑器 →
'          右键工程 → 导入文件 → 选本 .bas。
' ============================================================

Option Explicit

' Main entry: export every section in the active document to its own PDF.
' 主入口：导出当前活动文档的所有节为独立 PDF。
Sub ExportPDFs_OnePerSection()
    ' Function: split the "Mail Merge → Edit Individual Documents" output
    '           into one PDF per record, by Section.
    ' Prereq : Mail Merge type must be "Letters" (inserts section breaks
    '           between records). Run AFTER "Edit Individual Documents".
    '
    ' 功能：把"邮件合并→编辑单个文档"生成的大文档按分节符切成独立 PDF。
    ' 前提：邮件合并类型必须是"信函"——它会在每条记录之间插入分节符。
    ' 用法：先完成邮件合并并"编辑单个文档"，再运行本宏。

    Dim doc As Document, newDoc As Document
    Dim sec As Section
    Dim i As Long
    Dim outPath As String
    Dim fso As Object

    '★ Change to a folder you can write to. Auto-created if missing.
    '★ 改成你有写权限的文件夹；不存在会自动建。
    outPath = "C:\ExportedPDFs\"

    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(outPath) Then fso.CreateFolder outPath

    Set doc = ActiveDocument
    i = 0
    Application.ScreenUpdating = False

    ' Sanity check: a single section means the merge was probably not done.
    ' 节数自检：1 节多半是忘了做"编辑单个文档"。
    If doc.Sections.Count < 2 Then
        MsgBox "Only " & doc.Sections.Count & " section(s) detected." & vbCr & _
               "Please confirm: 'Start Mail Merge' was set to 'Letters'," & _
               " and 'Finish & Merge → Edit Individual Documents' was run." & vbCr & _
               "(A single-record document with 1 section is fine.)", _
               vbExclamation, "B07 Export"
    End If

    For Each sec In doc.Sections
        i = i + 1
        sec.Range.Copy                ' Copy this section (one letter)
                                      ' 复制这一节（一封信）
        Set newDoc = Documents.Add    ' Blank document
                                      ' 新建空白文档
        newDoc.Range.Paste            ' Paste directly (more reliable than Selection.Paste)
                                      ' 直接粘贴，比 Selection.Paste 更稳

        newDoc.ExportAsFixedFormat _
            OutputFileName:=outPath & "Notice_" & i & ".pdf", _
            ExportFormat:=wdExportFormatPDF

        newDoc.Close SaveChanges:=False
    Next sec

    Application.ScreenUpdating = True
    MsgBox "Done. Exported " & i & " PDF(s) to " & outPath, _
           vbInformation, "B07 Export"
End Sub


' Optional helper: name each PDF by recipient name (instead of 1, 2, 3, …)
' 可选辅助：按收件人姓名命名 PDF。
Sub ExportPDFs_NamedByRecipient()
    Dim doc As Document, newDoc As Document
    Dim sec As Section
    Dim i As Long
    Dim outPath As String
    Dim fso As Object
    Dim nameField As String
    Dim safeName As String

    outPath = "C:\ExportedPDFs\"

    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(outPath) Then fso.CreateFolder outPath

    Set doc = ActiveDocument
    i = 0
    Application.ScreenUpdating = False

    If doc.Sections.Count < 2 Then
        MsgBox "Run Mail Merge first, then 'Edit Individual Documents'.", vbExclamation
        Exit Sub
    End If

    For Each sec In doc.Sections
        i = i + 1
        sec.Range.Copy
        Set newDoc = Documents.Add
        newDoc.Range.Paste

        ' Read the first MERGEFIELD (Name) and sanitize for file names.
        ' 读第一个合并域（姓名），并对文件名做安全过滤。
        On Error Resume Next
        nameField = newDoc.Fields(1).Result.Text
        On Error GoTo 0

        safeName = Replace(nameField, vbCr, "")
        safeName = Replace(safeName, vbLf, "")
        safeName = Replace(safeName, vbTab, "")
        safeName = Replace(safeName, "\", "_")
        safeName = Replace(safeName, "/", "_")
        safeName = Replace(safeName, ":", "_")
        safeName = Replace(safeName, "*", "_")
        safeName = Replace(safeName, "?", "_")
        safeName = Replace(safeName, """", "_")
        safeName = Replace(safeName, "<", "_")
        safeName = Replace(safeName, ">", "_")
        safeName = Replace(safeName, "|", "_")

        If Len(safeName) = 0 Then safeName = "Record_" & i   ' Fallback name
                                                        ' 姓名空时的兜底

        newDoc.ExportAsFixedFormat _
            OutputFileName:=outPath & safeName & ".pdf", _
            ExportFormat:=wdExportFormatPDF

        newDoc.Close SaveChanges:=False
    Next sec

    Application.ScreenUpdating = True
    MsgBox "Done. Exported " & i & " PDF(s) to " & outPath, _
           vbInformation, "B07 Export"
End Sub