Модификация AcroForm

Следующий фрагмент кода также работает с библиотекой Aspose.PDF.Drawing.

Получить или установить лимит поля

Метод SetFieldLimit(field, limit) класса FormEditor позволяет установить лимит поля, максимальное количество символов, которые можно ввести в поле.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SetFieldLimit()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Create FormEditor instance
    using (var form = new Aspose.Pdf.Facades.FormEditor())
    {
        // Bind PDF document
        form.BindPdf(dataDir + "input.pdf");

        // Set field limit for "textbox1"
        form.SetFieldLimit("textbox1", 15);

        // Save PDF document
        form.Save(dataDir + "SetFieldLimit_out.pdf");
    }
}

Аналогично, Aspose.PDF имеет метод, который получает лимит поля с использованием подхода DOM. Следующий фрагмент кода показывает шаги.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetFieldLimitUsingDOM()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "FieldLimit.pdf"))
    {
        // Get the field and its maximum limit
        if (document.Form["textbox1"] is Aspose.Pdf.Forms.TextBoxField textBoxField)
        {
            Console.WriteLine("Limit: " + textBoxField.MaxLen);
        }
    }
}

Вы также можете получить то же значение, используя пространство имен Aspose.Pdf.Facades с помощью следующего фрагмента кода.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetFieldLimitUsingFacades()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Create Form instance
    using (var form = new Aspose.Pdf.Facades.Form())
    {
        // Bind PDF document
        form.BindPdf(dataDir + "FieldLimit.pdf");

        // Get the field limit for "textbox1"
        Console.WriteLine("Limit: " + form.GetFieldLimit("textbox1"));
    }
}

Установить пользовательский шрифт для поля формы

Поля формы в файлах Adobe PDF могут быть настроены для использования определенных шрифтов по умолчанию. В ранних версиях Aspose.PDF поддерживались только 14 шрифтов по умолчанию. Поздние релизы позволили разработчикам применять любой шрифт. Чтобы установить и обновить шрифт по умолчанию, используемый для полей формы, используйте класс DefaultAppearance(Font font, double size, Color color). Этот класс можно найти в пространстве имен Aspose.Pdf.InteractiveFeatures. Чтобы использовать этот объект, используйте свойство DefaultAppearance класса Field.

Следующий фрагмент кода показывает, как установить шрифт по умолчанию для полей формы PDF.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SetFormFieldFont()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "FormFieldFont14.pdf"))
    {
        // Get particular form field from document
        if (document.Form["textbox1"] is Aspose.Pdf.Forms.Field field)
        {
            // Create font object
            var font = Aspose.Pdf.Text.FontRepository.FindFont("ComicSansMS");

            // Set the font information for form field
            field.DefaultAppearance = new Aspose.Pdf.Annotations.DefaultAppearance(font, 10, System.Drawing.Color.Black);
        }

        // Save PDF document
        document.Save(dataDir + "FormFieldFont14_out.pdf");
    }
}

Добавление/удаление полей в существующей форме

Все поля формы содержатся в коллекции Form объекта Document. Эта коллекция предоставляет различные методы для управления полями формы, включая метод Delete. Если вы хотите удалить конкретное поле, передайте имя поля в качестве параметра методу Delete, а затем сохраните обновленный PDF документ. Следующий фрагмент кода показывает, как удалить конкретное поле из PDF документа.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void DeleteFormField()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "DeleteFormField.pdf"))
    {
        // Delete a particular field by name
        document.Form.Delete("textbox1");

        // Save PDF document
        document.Save(dataDir + "DeleteFormField_out.pdf");
    }
}