Javascript для pdf форм

Как заполнить pdf документ из данных формы?

Есть форма на сайте. Пользователь заполняет её. Эти данные, из формы, вносятся в pdf файл в определенные места. Например, есть сертификат, готовый, в котором поле с ФИО пустое, пользователь вводит свое ФИО в input на сайте, и это ФИО попадает на сертификат в нужное место. Как взаимодействовать с pdf форматом с помощью, например, javascript , или есть ли какое нибудь API для редоктирования PDF или doc форматов?

2 ответа 2

Как я понял при помощи поиска, есть две стратегии:

1. Создание нового документа.

Вот в этом руководстве последовательно рассматриваются вопросы, начиная от подключения библиотеки, и заканчивая тем, как открывать сгенерированный документ в отдельном окне ajax’ом.

Вот эта статья на Хабре — довольно основательная, и на неё много ссылаются, но она уже старовата — это перевод 2008-го года.

Я мог бы скопировать код из этих руковоств в ответ, но, по моему, оригинальные статьи будут полезее.

2. Использование темплейта, в котором будут заполнены тоько некоторые поля

Это довольно несложный процесс, можно даже привести пример кода, котрый вписывает в документ фразу:

 setSourceFile('template.pdf'); $tpl = $pdf->importPage(1); $pdf->addPage(); $pdf->useTemplate($tpl); setXY(10, 20); $pdf->write(100, "Hi there"); output('newpdf.pdf', 'D');

Вообще говоря, это просто пример кода с англоязычной части SO: «Is there a solution for pdf template in PHP?»

Также, если у Вас возникнут более конкретные вопросы — милости просим, или welcome!

Источник

How to add JavaScript to PDF forms?

I am absolutely newbie in Javascript. I have a form in PDF and want to add a Javascript action to it. Let’s say I want an alert comes up when someone clicks on a check box. Here is what I do: 1-first open the form in Acrobat Pro -> Tools-> Form -> edit: enter image description here2-then click on a checkbox-> Properties enter image description hereand select action -> Run Java Script enter image description hereand added this code:

   

enter image description here

After saving , nothing happens when I click on this checkbox. I am not sure if my Java code is wrong or I am missing something in the Acrobat Pro or something ?!

You don’t need

1 Answer 1

Welcome to scripting PDFs.

First and foremost, Java and JavaScript are not the same. All they have in common are three characters.

Second, JavaScript is much more than what they tell you it is when using it in webbrowsers. JavaScript consists of the Core and the application-specific extensions. Webbrowser JavaScript consists of the Core and the webbrowser-specific extensions. This is shown best in Flanagan’s JavaScript, the Defnitve Guide, published by O’Reilly.

So, Acrobat JavaScript consists of the Core and the Acrobat-specific extensions. Those are documented in the Acrobat JavaScript documentation, which is part of the Acrobat SDK, downloadable from the Adobe website.

Then, there is the object model playing another role. This is also described in the Acrobat JavaScript documentation.

I insist on this documentation, because that’s what you need to have at hand, and you should have at least quickly read through the Guide and glanced at the Reference (which does have code samples).

Then you will see that the code you tried — which is syntactically correct JavaScript — simply does not work in Acrobat.

Actually, it seems that you wanted a checkbox to pop up an alert saying «Hello World» when being checked. Actually, you got to the correct event to use; using the MouseUp event for clicking is how the document object model in PDF forms works.

One possibility to make appear the alert box would actually look like this:

There would be other ways do do it when you are using another field to contain the code.

Источник

Generating Interactive PDF Forms by Injecting JavaScript

Using TX Text Control, it is possible to export documents with form fields to fillable PDFs. This article shows how to inject JavaScript to add interaction to form fields.

TX Text Control provides a way to create documents with fillable form elements, such as form text boxes, check box fields and drop-down elements. Documents with form elements can be created similar to mail merge templates and dynamically pre-completed with known values. This helps to generate custom forms where some fields are already completed with known values to accelerate the completion process and to improve the user experience.

Using TX Text Control, PDF documents can be easily created, shared and collected in business applications. PDF forms with fillable form elements can be created and collected by reading the completed documents in order to analyze and store the data.

In various applications, it might be be useful to add interaction to form fields in the PDF document. Consider a text field that should contain the current date at the time the document is opened. TX Text Control is able to export the PDF documents with those fillable form fields including additional JavaScript to control the interaction between fields. Technically, any document level JavaScript can be embedded using the Save Settings ╰ TX Text Control .NET Server for ASP.NET
╰ TXTextControl Namespace
╰ SaveSettings Class
The SaveSettings class provides properties for advanced settings and information during save operations. class and the Document Level Java Script Actions ╰ TX Text Control .NET Server for ASP.NET
╰ TXTextControl Namespace
╰ SaveSettings Class
╰ DocumentLevelJavaScriptActions Property
Specifies an array of strings containing Javascript. property.

The following code loads a JavaScript code text file in order to embed it to a PDF document:

JavaScript API Reference

You can download the full Adobe JavaScript API Reference directly from Adobe.

acrobatsdk_jsapiref.pdf

Use Cases

In the following use cases, typical scenarios are explained where JavaScript can be used to add logic and interaction to form fields.

Populating Form Text Fields

Consider a form text field that should be populated with the current date at the time the user is opening this document.

Fillable Forms with Text Control

The following JavaScript is populating the form text field with the name MyDateField with the current (client-side) date string. Additionally, the required property makes this field mandatory.

When opening this document in Acrobat Reader (or any other PDF viewer), the form text field contains the current date:

Fillable Forms with Text Control

Adding Events

In the next example, the value of a form text field should be changed when the state of a checkbox is changed. The following screenshot shows a template with 2 checkboxes and 2 form text fields:

Fillable Forms with Text Control

In the following JavaScript code, the MouseUp event is attached to both checkboxes to call the function validate. The MouseUp is not only fired for mouse actions, but keyboard actions as well. In the attached event handler, the value of the associated form text field is changed depending on the check state.

Conditional Changes

In this scenario, a form text field is enabled in case a specific value of a drop-down box is selected (Other in this case). The following JavaScript is adding the conditional logic to the associated form fields:

Conclusion

Using TX Text Control, it is possible to create and deploy forms with additional logic. These forms can be deployed using the DocumentEditor, the DocumentViewer or using a PDF to collect user form data. Using embedded JavaScript code, it is possible to add workflows, logic and validation to form fields in PDF documents.

ASP.NET

The first true WYSIWYG, HTML5-based Web editor and reporting template designer. Give your users an MS Word compatible editor to create powerful reporting templates anywhere — in any browser on any device. Our ASP.NET components combine the power of a reporting tool and an easy-to-use WYSIWYG word processor — fully programmable and embeddable in your ASP.NET application.

Sneak Peek 32.0: Modifying the Normal Stylesheet

Stylesheets in TX Text Control provide a powerful tool for maintaining consistency and ensuring that documents look and feel professional. In version 32.0 it will be possible to manipulate the root style «Normal». This will allow better global formatting changes.

Sneak Peek 32.0: Introducing Footnotes

Footnotes are a word processing feature that allows users to insert additional information at the bottom of pages. We will introduce this MS Word compatible, fully programmable feature to TX Text Control with version 32.0.

Service Pack 3 for TX Text Control 31.0 Released

We are very happy to announce the immediate availability of new Service Packs for all TX Text Control 31.0 products to address various bugs and issues reported by our valued users.

An Ultimate Guide to Mail Merge with MS Word Documents in C#

The MailMerge class provides very effective ways to merge data into MS Word compatible templates. This updated ultimate guide provides an overview of all the important features and functionalities of the mail merge process.

Источник

Читайте также:  Java многопоточность метод join
Оцените статью