Search code examples
c#pdfitext7

How to rotate input field of the pdf document with C#?


I have a pdf file with some text input fields. I've installed the itext7 (8.0.4) nuget package for C# to work with pdf files and I need to fill in the text fields and then rotate them around 25 degrees.

I asked chatgpt for a solution, and it came up with this:

using iText.Forms.Fields;
using iText.Kernel.Pdf;

PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter("output.pdf"));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

PdfFormField field = form.GetField("fieldName");
field.SetRotation(90); // Set rotation angle in degrees

pdfDoc.Close();

but there is no SetRotation method for PdfFormField. This is the main issue.

I am VERY new to C#, I mostly did Vue components with typescript so I can't properly navigate this issue.

On the offhand discussion - I am really close to just creating my own PDF library (probably shouldn't do that) - are there any good tutorials for creating pdf files from scratch? :)

Maybe I'm overthinking it too much. Maybe it would be easier to just convert the text field to plain text and rotate it instead? I don't need fields to stay as fields after I've filled them in.

SOLUTION (Based on mkl response):

var widget = field.GetWidgets()[0];
var chars = new PdfDictionary();
chars.Put(PdfName.R, new PdfNumber(degrees));
widget.SetAppearanceCharacteristics(chars); 

Solution

  • You can set a rotation value for a field widget using the appearance characteristics dictionary of the widget:

    Key Type Value
    R integer (Optional) The number of degrees by which the widget annotation shall be rotated counterclockwise relative to the page. The value shall be a multiple of 90. Default value: 0.

    (ISO 32000-2, Table 192 — Entries in an appearance characteristics dictionary)

    The iText class PdfWidgetAnnotation has a setAppearanceCharacteristics method with which you can set a dictionary with an R value.

    Concerning your request

    I need to fill in the text fields and then rotate them around 25 degrees.

    You can try to set the transformation matrices of the generated appearances to a rotation by that angle.

    Unfortunately, though, this is not expected behavior by a PDF processor; in particular when filling text fields, a PDF processor is expected to set the appearance stream dictionary entries (except Resources and BBox) to their respective default value (see ISO 32000-2, section 12.7.4.3 Variable text). Consequentially, PDF viewers don't expect such special rotations in the Matrix entry and may ignore it.

    In a quick test Chrome accepted the Matrix entry while Adobe Acrobat ignored it.