Search code examples
javapdfbox

Add form fields to a rotated page in pdfBox


I have a requirement to add adobe form fields to an existing pdf.

The problem I encounter is when adding fields to a rotated page, the resulting form field text orientation is incorrect.

e.g. A page that is rotated 90 degrees clockwise, results in form field where the text is "vertical". page rotated 90 degrees results in text having 90 orientation

Is there a workaround to get form fields created with the correct orientation?


Solution

  • The appearance characteristics dictionary (/MK entry) of the widget has an /R entry where the rotation can be set. See e.g. this file.

    PDAppearanceCharacteristicsDictionary fieldAppearance
            = new PDAppearanceCharacteristicsDictionary(new COSDictionary());
    fieldAppearance.setRotation(90);
    widget.setAppearanceCharacteristics(fieldAppearance);
    

    You may have to adjust your coordinates. To find the best coordinates, use PDFDebugger and hover at the place you want your field to be.

    Update: For checkmarks (and radio buttons) where the appearance stream is created by the user and not by PDFBox (as seen here or in the PDFBox example) you need to set the matrix yourself like this (for 90°):

    yesAP.setMatrix(AffineTransform.getQuadrantRotateInstance(1, rect.getWidth(), 0));
    

    The "1" here is for 90°. The translation needs to be adjusted for the other rotations.