admin管理员组

文章数量:1431391

Adding header to a PDF with VBA, Field

I have several hundred pdf files and I want to add two part header to each of them. The text is initially coming from Excel, but in this example it is a static text. I wrote the following procedure with VBA?

Sub addHeader()

    Dim wdoc As String
    Dim Header_1 As String
    Dim Header_2 As String
    Dim Save As String
   
    Dim AcroApp As Acrobat.AcroApp
    Dim pdDoc As Acrobat.AcroPDDoc
    Dim jso As Object
    
    wdoc = "D:\VBA\test.pdf"
    Header_1 = "How to add text to a pdf file using VBA - Java Script. Can someone please give me an example"
    Header_2 = "Right side"
    Save = "D:\VBA\test_header.pdf"

    If (AcroApp Is Nothing) Then
        Set AcroApp = CreateObject("AcroExch.App")
    End If
    
    Set pdDoc = CreateObject("AcroExch.PDDoc")
        
    If pdDoc.Open(wdoc) Then
       
        Set jso = pdDoc.GetJSObject
                
        Set Box1 = jso.addField("H_left", "text", 0, Array(27, 842, 482, 827))
        Box1.textFont = "Times-Bold"
        Box1.textSize = 12
        Box1.TextColor = jso.Color.blue
        Box1.Value = Header_1
        'Box1.strokeColor = jso.Color.blue

        
        Set Box2 = jso.addField("H_right", "text", 0, Array(487, 842, 595, 827))
        Box2.textFont = "Times-Bold"
        Box2.textSize = 12
        Box2.TextColor = jso.Color.black
        Box2.Value = Header_2
        'Box2.strokeColor = jso.Color.black

    
    jso.flattenPages
       
    End If
    
    If pdDoc.Save(PDSaveFull, Save) = True Then
        MsgBox "Done"
    Else: MsgBox "Error"
    End If
    
    pdDoc.Close
    AcroApp.Exit
    
    Set pdDoc = Nothing
    Set jso = Nothing

End Sub

The procedure opens the pdf, creates two fields, assign text to each field, flattenPages and saves the document.

example

Note: Excel 365 Adobe Acrobat Pro installed

Everything works fine, but if I manually open the document after processing and try to move the text object (or block of text, I don't know the exact term used) a part of the text disappears, and if I try to resize the object the text appears with a strange alignment!

Also, even though I have two fields (Box1, Box2), after flattening they are merged into one text object. Only if I shorten the text like

Header_1 = "How to add text to a pdf file using VBA - Java Script. Can someone please give me an ex" 'ample"

and increase the spacing between fields to at least 17 points

Set Box2 = jso.addField("H_right", "text", 0, Array(499, 842, 595, 827))

after flattening they are not merged.

Is there any way to force the API to always keep these two fields separate after flattening?

How to format this fields so that after pdf flattening, text object don't lose alignment when they are moved around the page?

本文标签: javascriptAdding header to a PDF with VBAFieldStack Overflow