Search code examples
javascriptacrobatacrobat-sdk

Linespacing in multiline fields


I am trying to adjust the linespacing in a multiline pdf form field. These are the things I have already tried:

Using a rich text field and adjust the linespacing trough the "Form Field Text Properties" toolbar: This worked, but the changes get lost when you reset the form.

Using JavaScript: I added a keystroke event to the multiline text fields.

var spans = event.richValue;
if (spans !== undefined) {
    for ( var i = 0; i < spans.length; i++ ) {
        spans[i].linespacing = 14; // linespacing
    }
    event.richValue = spans;
}

With this script the linespacing works just fine, but it is not possible anymore to manually insert line breaks. They get removed as soon as event.richValue = spans is executed.

Last thing I tried was a slightly modified version of the script:

var spans = event.richValue;
if (spans !== undefined) {
    for ( var i = 0; i < spans.length; i++ ) {
        spans[i].linespacing = 14; // linespacing
        if (i < spans.length - 1) spans[i].text += "\r";
    }
    event.richValue = spans;
}

I tried to fix the disappearing line breaks by adding a "\r" at the end of every span. Turns out that Acrobat also treats double-spaces as a single span, so this script adds a line break after two spaces.

Is there a way to permanently set the linespacing in a multiline text field without messing up everything?


Solution

  • I think I found a solution by myself. After taking a closer look at the SPAN properties, I stumbled upon endParagraph.

    This is my final custom keystroke script:

    var spans = event.richValue;
    if (spans !== undefined && event.willCommit) {
        for ( var i = 0; i < spans.length; i++ ) {
            spans[i].textSize = 9; // font size
            spans[i].linespacing = 14; // linespacing
    
            // restore line breaks
            if (spans[i].endParagraph) spans[i].text += "\r";
    
            // reset styles to default
            spans[i].fontStyle = "normal";
            spans[i].fontWeight = 400;
            spans[i].strikethrough = false;
            spans[i].underline = false;
            spans[i].textColor = color.black;
            spans[i].alignment = "left";
            spans[i].fontFamily = ["Arial"];
        }
    
        event.richValue = spans;
    }
    

    I did not do much testing, but it looks like this solution works properly.