how to work with scripts and the pdf document api in sap interactive forms by adobe

19
SAP NetWeaver How-To Guide How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe Applicable Releases: SAP NetWeaver Composition Environment 7.1 Enhancement Pack 1 Topic Area: User Productivity Capability: User Interface Technology Version 1.0 April 2009

Upload: -

Post on 14-Apr-2015

69 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

SAP NetWeaver How-To Guide

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

Applicable Releases:

SAP NetWeaver Composition Environment 7.1 Enhancement Pack 1

Topic Area: User Productivity

Capability: User Interface Technology

Version 1.0

April 2009

Page 2: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

© Copyright 2009 SAP AG. All rights reserved.

No part of this publication may be reproduced or

transmitted in any form or for any purpose without the

express permission of SAP AG. The information contained

herein may be changed without prior notice.

Some software products marketed by SAP AG and its

distributors contain proprietary software components of

other software vendors.

Microsoft, Windows, Outlook, and PowerPoint are

registered trademarks of Microsoft Corporation.

IBM, DB2, DB2 Universal Database, OS/2, Parallel

Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390,

OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP,

Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix,

i5/OS, POWER, POWER5, OpenPower and PowerPC are

trademarks or registered trademarks of IBM Corporation.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader

are either trademarks or registered trademarks of Adobe

Systems Incorporated in the United States and/or other

countries.

Oracle is a registered trademark of Oracle Corporation.

UNIX, X/Open, OSF/1, and Motif are registered

trademarks of the Open Group.

Citrix, ICA, Program Neighborhood, MetaFrame,

WinFrame, VideoFrame, and MultiWin are trademarks or

registered trademarks of Citrix Systems, Inc.

HTML, XML, XHTML and W3C are trademarks or

registered trademarks of W3C®, World Wide Web

Consortium, Massachusetts Institute of Technology.

Java is a registered trademark of Sun Microsystems, Inc.

JavaScript is a registered trademark of Sun Microsystems,

Inc., used under license for technology invented and

implemented by Netscape.

MaxDB is a trademark of MySQL AB, Sweden.

SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP

NetWeaver, and other SAP products and services

mentioned herein as well as their respective logos are

trademarks or registered trademarks of SAP AG in

Germany and in several other countries all over the world.

All other product and service names mentioned are the

trademarks of their respective companies. Data contained

in this document serves informational purposes only.

National product specifications may vary.

These materials are subject to change without notice.

These materials are provided by SAP AG and its affiliated

companies ("SAP Group") for informational purposes only,

without representation or warranty of any kind, and SAP

Group shall not be liable for errors or omissions with

respect to the materials. The only warranties for SAP

Group products and services are those that are set forth in

the express warranty statements accompanying such

products and services, if any. Nothing herein should be

construed as constituting an additional warranty.

These materials are provided “as is” without a warranty of

any kind, either express or implied, including but not

limited to, the implied warranties of merchantability,

fitness for a particular purpose, or non-infringement.

SAP shall not be liable for damages of any kind including

without limitation direct, special, indirect, or consequential

damages that may result from the use of these materials.

SAP does not warrant the accuracy or completeness of the

information, text, graphics, links or other items contained

within these materials. SAP has no control over the

information that you may access through the use of hot

links contained in these materials and does not endorse

your use of third party web pages nor provide any warranty

whatsoever relating to third party web pages.

SAP NetWeaver “How-to” Guides are intended to simplify

the product implementation. While specific product

features and procedures typically are explained in a

practical business context, it is not implied that those

features and procedures are the only approach in solving a

specific business problem using SAP NetWeaver. Should

you wish to receive additional information, clarification or

support, please refer to SAP Consulting.

Any software coding and/or code lines / strings (“Code”)

included in this documentation are only examples and are

not intended to be used in a productive system

environment. The Code is only intended better explain and

visualize the syntax and phrasing rules of certain coding.

SAP does not warrant the correctness and completeness of

the Code given herein, and SAP shall not be liable for

errors or damages caused by the usage of the Code, except

if such damages were caused by SAP intentionally or

grossly negligent.

Disclaimer

Some components of this product are based on Java™. Any

code change in these components may cause unpredictable

and severe malfunctions and is therefore expressively

prohibited, as is any decompilation of these components.

Any Java™ Source Code delivered with this product is only

to be used by SAP’s Support Services and may not be

modified or altered in any way.

Page 3: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

Document History Document Version Description

1.00 First official release of this guide

Page 4: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

Typographic Conventions Type Style Description

Example Text Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.

Cross-references to other documentation

Example text Emphasized words or phrases in body text, graphic titles, and table titles

Example text File and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.

Example text User entry texts. These are words or characters that you enter in the system exactly as they appear in the documentation.

<Example text>

Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.

EXAMPLE TEXT Keys on the keyboard, for example, F2 or ENTER.

Icons Icon Description

Caution

Note or Important

Example

Recommendation or Tip

Page 5: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

Table of Contents

1. Scenario................................................................................................................................ 1

2. Downloadable Examples .................................................................................................... 1

3. Prerequisites ........................................................................................................................ 2

4. Simple Scripting .................................................................................................................. 3 4.1 Overview of Basic LiveCycle Designer Concepts ........................................................ 3

4.1.1 Binding scripts to UI events ............................................................................. 4 4.1.2 Setting Up the Form for Scripting .................................................................... 4

4.2 Controlling the Visibility of a UI Element ...................................................................... 5 4.3 Adding Rows to a Table Dynamically........................................................................... 6 4.4 Calculating a Summation in a Table............................................................................. 8

5. Using the PDF Document API ............................................................................................ 8 5.1 Template and Data ....................................................................................................... 9

5.1.1 Working with an Existing PDF: IWDPDFDocumentAccessibleContext......... 10 5.1.2 Creating a PDF Dynamically: IWDPDFDocumentCreationContext............... 11 5.1.3 Working with Resource Objects..................................................................... 11

5.2 Document Attachments .............................................................................................. 12

6. Appendix ............................................................................................................................ 13

Page 6: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

1. Scenario The end-user experience of a PDF form can be enhanced through the addition of dynamic behavior via the scripting features available to the developer in Adobe LiveCycle Designer. As opposed to their paper counterparts, PDF documents can be context-aware and react to user input to provide the user a more meaningful and accessible interface. This guide shows you how to implement some of the more commonly requested dynamic features, such as controlling the visibility of controls, expanding tables as needed, and calculating sums in tables.

Beyond these dynamic features that can be implemented by scripting, SAP Interactive Forms by Adobe allow the use of more advanced features of PDF documents, such as the dynamic construction of PDFs from templates and data. This is useful when connecting to a backend that delivers data in XML format or in a format that can be easily transformed to XML, as well as features such as attachments to PDFs, which allow the enriching of PDF documents with extra data in file form. This can be particularly useful when delivering forms for offline use, since all required data, including extra files required by the end user, can be bundled in a single PDF instead of an archive or multiple files.

2. Downloadable Examples You can download the code examples provided with this guide from SDN. There are three Web Dynpro development component projects contained in the archive.

To work with the projects, you will have to unzip the archive and place the contents into your Developer Studio’s JDI directory. If your workspace is C:\folder\workspace, then the JDI directory is C:\folder\workspace.jdi.

Beneath this folder, you should have a path LocalDevelopment\DCs\demo.sap.com. Inside the archive, you will find a directory called “example”. Place the “example” directory inside the “demo.sap.com” directory, so that the full path is C:\folder\workspace.jdi\LocalDevelopment\DCs\demo.sap.com\example.

Within this directory, you should have three folders: pdfapi, scripting, and attachments. These are the three example projects.

You now need to import the projects into NWDS. ...

1. Open the Development Infrastructure perspective in NWDS. You can do this in the Window menu, under Open Perspective.

2. Browse down through Local Development/My Components [demo.sap.com] and open the tree structure. You should see your three projects: example/attachments, example/pdfapi, example/scripting. If you do not see the projects, press F5 to reload the project listing. Select all three projects.

April 2009 1

Page 7: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

3. Right-click on the projects and select Sync / Create Project from the context menu. In the submenu that opens, select Create Project.

4. If you are prompted to Create DC Projects (Sync Sources and Used DCs), select OK.

5. You will be prompted to switch to the Web Dynpro perspective. Select OK to begin working with the projects.

3. Prerequisites This guide was put together using the following software versions. You may find that if you are using older versions, not all features will work or be present (but you can try!):

• Adobe Reader 9.1

• SAP NetWeaver Composition Environment 7.1 Enhancement Package 1 (including NetWeaver Developer Studio)

• Adobe LiveCycle Designer 8.1

Please note that this guide assumes familiarity with the SAP Interactive Forms by Adobe product, NetWeaver Developer Studio and Web Dynpro. This guide is not meant as an introduction to these topics.

April 2009 2

Page 8: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

April 2009 3

4. Simple Scripting This section gives examples of common uses of the scripting features of PDFs. The examples are built in Adobe LiveCycle Designer. Since these are examples of client-side scripting functionality, they can also be run (previewed) in Adobe LiveCycle Designer without deploying the Web Dynpro application to the server.

These scripts use the XML Form Object Model to manipulate user interface elements and data at runtime. The basics of using scripting are documented in LiveCycle Designer Help, delivered with your installation of Adobe LiveCycle Designer, and accessible in the Help menu. The XML Form Object Model is documented extensively in the Adobe XML Form Object Model Reference.

Most of these examples use JavaScript. A second language, FormCalc, is available for scripting when appropriate. FormCalc contains a number of useful built-in functions, including financial functions that would otherwise need to be implemented by the developer. LiveCycle Designer Help contains an entry entitled Choosing a scripting language that outlines the major differences between the two languages.

4.1 Overview of Basic LiveCycle Designer Concepts

Figure 1: LiveCycle Designer within SAP NetWeaver Developer Studio

The figure above shows LiveCycle Designer as it appears when working with forms as part of Web Dynpro. For clarity, the SAP NetWeaver Developer Studio user interface elements are not shown in the figure.

Tip When working with Adobe LiveCycle Designer in SAP NetWeaver Developer Studio, maximize the LiveCycle Designer tool’s screen area. You can do this by double-clicking on the NetWeaver Developer Studio tab that contains LiveCycle Designer (in the figure

Event dropdown

Script area Language selector

UI library

Design view

Form’s element tree

Page 9: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

below, this tab is labeled “PurchaseForm”). Double-click on the tab again to return to the original size.

The center of the screen is the design view, where the form is shown as it is being edited. As you work with the form, you’ll be placing user interface elements on it. The hierarchy of user interface elements currently on the form is shown to the left of the design view, in the Hierarchy tab. A form may consist of nested subforms. Subforms allow you to split your form into smaller pieces. This is especially useful when controlling the visibility of a group of form elements in a script, as we’ll see later. The hierarchy of user interface elements shown in the Hierarchy tab shows the use of subforms (“MainSubform”, “TableSubform” and “AddressSubform”).

The Library tab to the right of the design view contains the developer’s palette of available UI elements that can be used on the form.

4.1.1 Binding scripts to UI events User interface elements, such as input fields, drop-down boxes or checkboxes, have events associated with their use. For instance, marking a checkbox triggers that checkbox’s click event. A script can be bound to these events.

In order to bind the events of a UI element to a script, select the UI element. The top area of the LiveCycle Designer tool is used to work with scripts. At the top left, a dropdown box contains the list of events applicable to the selected UI element. The script area beneath the dropdown shows the source of the script that is bound to the selected event. Since scripts can be written in either JavaScript or FormCalc, a dropdown at the top right of the script area shows the currently selected language. This guide will deal only with client-side scripting (this can be set in the dropdown next to the language selector).

Tip A common mistake when starting out with scripting is to select the wrong language, e.g. FormCalc when entering JavaScript. Also be aware that the first line in the script area is not editable and isn’t part of the script (in case you are copying script from examples, be sure not to try and copy that line). This first line shows the currently selected object and event.

4.1.2 Setting Up the Form for Scripting Incorrect settings in LiveCycle Designer can prevent the dynamic features discussed in this document from previewing correctly. To ensure that the form will work correctly when using the Preview tab in LiveCycle Designer, open the form properties by going to the Edit menu and selecting Form Properties. Select the Preview tab and ensure that Preview Type is set to Interactive Form. The other options prevent interactive elements (dropdowns, input fields, etc) from working during form preview. Also make sure that Preview Adobe XML Form As is set to Dynamic XML Form. The Static PDF Form option prevents dynamic elements (such as automatically expanding tables) from working correctly when previewing the form.

April 2009 4

Page 10: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

Once you have made these changes, you will be able to use the Preview tab in LiveCycle Designer to test your scripting work.

In order for the form to behave correctly once it has been deployed to the server, the PDF Render Format needs to be set to Dynamic XML Form. This is found on the Defaults tab in the Form Properties window.

4.2 Controlling the Visibility of a UI Element

The end-user’s experience can (sometimes) be improved by showing hidden information on the form when it is relevant to the user and keeping it hidden when it is not relevant. The figure below shows an example of a form that would benefit from this approach.

April 2009 5

Page 11: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

The Delivery Address should be shown only when the Check if you need delivery checkbox at the top of the form is marked. Otherwise, it should be invisible.

Since the information to be hidden contains a number of UI elements, it’s best to group them in a subform. Then, instead of dealing with each UI element individually, the visibility of the subform can be controlled in the script.

The visibility of a subform (or other UI element) can be controlled by setting the presence string property to “visible” or “invisible”.

Here is a simple example of how this works. Follow the steps below to create a simple form with one checkbox and one text element wrapped in a subform. Marking the checkbox will hide the subform containing the text element. ...

1. On a new form, drag a Check Box element onto the form design area

2. Drag a Text element onto the form

3. In the Hierarchy view to the left of the design area, right-click on the Text element (probably named “Text1” unless you gave it a different name) and select Wrap in Subform from the context menu.

4. Select the subform in the Hierarchy view and rename it to mysubform

5. In the Hierarchy view, select the check box (CheckBox1)

6. Select click from the event drop-down at the top of the script area

7. You can now enter the desired script into the script area and it will be bound to the click event of the checkbox. When editing the script, you can ctrl-click on a UI element in the design view and that element’s reference is inserted into the script.

if( this.rawValue == 0 )

{

mysubform.presence = "invisible";

}

else

{

mysubform.presence = "visible";

}

In order to try this example, switch to the Preview PDF tab at the top of the area currently showing the Design View. This previews the PDF as it would be rendered for the end user.

Marking and unmarking the checkbox shows and hides the text area, as expected. But the text area should be hidden initially, since the box is initially unchecked. You can do this by editing the subform’s properties and setting the presence to Invisible. To do this, click on the subform and work in the Object palette, located to the right of the design view. There you can set the Presence dropdown to Invisible.

Also try to place multiple UI elements within the subform. You’ll see that they appear and disappear as a group. }

4.3 Adding Rows to a Table Dynamically It can be useful to provide the user of a form with the ability to add rows to a table. This is useful when the user needs to enter a variable amount of tabular data (e.g. when it’s not clear how many data items the user will enter during form design time).

April 2009 6

Page 12: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

A table row is a subform and therefore has all the properties and methods of a regular subform. In order to add a row to an existing table, a new instance of an existing row is made using the row subform’s instanceManager object.

So, for example, if you have a table called Table1 on your form, and that table has a row called Row1, you can add a row to the beginning of the table by using the following in your JavaScript:

Table1.Row1.instanceManager.insertInstance(0,true);

The arguments to the insertInstance method are the zero-indexed position in the list of rows and a boolean that controls whether or not existing data should be merged with the new row instance.

In order for this to work, you need to ensure that the table row is capable of repeating. In order to do this, select the row (easiest by selecting it in the Hierarchy view to the left of the design view) and open the Binding tab in the Object editor pane to the right of the design view. Make sure that the check box Repeat Row for Each Data Item is marked.

...

1. Drag a button and a table onto your form

2. Edit the button’s click event script and add the code given in the text above. Make sure that your object names match the code.

3. Edit the row’s binding and make sure it’s set to repeat for each data item

4. Preview the form and see that a new row is added to the table each time the button is pressed.

It makes sense to limit the number of rows that a table can have, since there is limited room on the form.

When developing forms for a Web Dynpro environment, the number of table rows to be displayed is controlled by the number of instances of the Web Dynpro context node the table row is bound to. For example, if you have five instances of the context node during runtime, the table on the PDF generated will have five table rows by default.

If you want to give your end users the ability to add rows to the table as required, treat the number of instances of Web Dynpro context nodes as the maximum number of rows in the table. Then, in the initialization script of your table’s subform, remove the rows you don’t want to display initially. This ensures that the server runtime has enough context nodes to receive your table’s dynamic row elements. ...

April 2009 7

Page 13: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

4.4 Calculating a Summation in a Table FormCalc’s built-in Sum function computes the sum of a set of numbers. Although it’s possible to do the same computation in JavaScript by implementing the summation logic, using FormCalc in this scenario is easier than implementing the equivalent function in JavaScript. (A single form may use scripts in both languages).

The code sample provided with this guide shows how to apply this technique to the dynamic table discussed in previous sections. The core of the functionality is within the exit hook script for the UnitPrice decimal field object. This field contains the unit price for a single item in the table. The exit hook script is called when focus is removed from the field, i.e. when the user moves the cursor out of the field. This occurs regardless of whether or not the user made changes to the contents of the field.

Here is the script that updates the Total field when the user moves focus out of the UnitPrice field.

Total.rawValue = Sum( Table1.Row1[*].UnitPrice )

The Sum function is called with all UnitPrice fields as its argument. Since the table can be dynamically expanded, there may be more than one UnitPrice field. In fact, there is one UnitPrice field for each instance of Row1 in the table (remember that rows are subforms, and that we added rows by creating another instance of an existing row). For this reason, the object names in the script are slightly misleading at first glance, because it appears as if only one row is taken into account (Row1), when in fact the summation set includes all existing rows (the “*” in the expression Table1.Row1[*].UnitPrice takes care of this).

Implementing this behavior is straightforward: ...

1. Select the field containing the value you wish to sum

2. Select the exit event in the events drop-down

3. Change the script language to FormCalc

4. Enter the script above, keeping in mind that your object names might differ. Total is the decimal field that displays the end sum, UnitPrice is the field that contains the value to sum.

Us

ing the PDF D

5. Using the PDF Document API The PDF document API allows the dynamic construction of new and manipulation of existing PDF document objects. The API allows the developer to access the PDF as a Java object and work with it programmatically. The API allows you to

• Create documents using a template (layout) and data. Template + data = PDF.

• Add attachments to documents

• Change the document appearance (hide menu bars, magnification)

• Digitally sign the document using a private key

• Change the dynamic mode of the document

• Extract data in XML form from an existing document

The API is found in the packages com.sap.tc.webdynpro.clientserver.adobe.api and com.sap.tc.webdynpro.clientserver.adobe.pdfdocument.api. Note that the classes in the com.sap.tc.webdynpro.pdfobject.api package are deprecated.

April 2009 8

Page 14: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

5.1 Template and Data Conceptually, a PDF is composed of a template, which controls the layout of controls and data, and XML data, which is typically obtained from a backend system, generated at render time, or entered by the user (this is much like the separation between layout and data used in XSLT processing, where XSL templates are combined with XML data to produce a document).

In a typical scenario, the template and data are combined during rendering to generate a PDF with which the user can interact. Generally this end-user interaction consists of changing the data in the form (working with field entries and drop-down values). When the form is submitted back to the server, the data is again separated from the template and evaluated. Typically this means that the Web Dynpro context structures are filled with the data from the form. Using the PDF document API, it’s possible to obtain XML data directly from the PDF object instead of reading it from the Web Dynpro context.

The template is in the XDP (XML Data Package) format. It’s not necessary to understand the details of the format to work with the PDF document API. If you are interested, you can learn more about the format by examining the contents of an XDP file (these are found under the appropriate component in the src/configuration/Components directory in your Web Dynpro project) and reading the XDP Specification, available at http://www.adobe.com).

When working in Adobe LiveCycle Designer, it’s possible to inspect the XDP contents of the PDF you are designing by using the XML Source tab.

If you don’t have this tab visible, you need to enable it in LiveCycle Designer’s View menu.

Opening the XDP file included in your Web Dynpro project reveals that it describes the user interface elements of the PDF form. It also contains the binding references to data elements. Here is an example of a TextEdit UI element named DestinationCity:

<field name="DestinationCity" y="127mm" x="19.05mm" w="101.6mm" h="9mm">

April 2009 9

Page 15: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

<ui> <textEdit> <border> <edge stroke="lowered"/> </border> <margin/> </textEdit> </ui> ... <bind match="dataRef" ref="$record.TravelData[*].DestinationCity"/>

</field>

In order to generate a PDF, this XDP is combined with free-form XML data. According to the bind element in the above sample, this XML data should contain a DestinationCity tag wrapped in a TravelData tag. Here is an example:

<TravelData> <ArrvialDate>2008-04-28</ArrvialDate> <DepartureDate>2008-04-30</DepartureDate> <DestinationCity>San Diego</DestinationCity> </TravelData>

The result of combining these two XML documents is a PDF with a TextEdit element called DestinationCity pre-filled with San Diego.

5.1.1 Working with an Existing PDF: IWDPDFDocumentAccessibleContext

The PDF document API distiginuishes between creating a new PDF and working with an existing PDF. Use the IWDPDFDocumentAccessibleContext interface to extract the XML data from an existing PDF (e.g. one that has been submitted to the server by a user). The following code snippet shows how to retrieve the IWDPDFDocumentAccessibleContext object. The context requires the PDF’s raw byte data for processing (myPDFByteArray). Once this has been set, the execute method is called to retrieve the IWDPDFDocument object:

IWDPDFDocumentHandler hdlr = WDPDFDocumentFactory.getDocumentHandler();

IWDPDFDocumentAccessibleContext cxt = hdlr.getDocumentAccessibleContext();

// myPDFByteArray is a byte [] containing // the raw PDF data ctx.setPDF( myPDFByteArray );

IWDPDFDocument theDocument = ctx.execute();

InputStream is = theDocument.getData();

The InputStream in the last line delivers the XML data as a stream (you will most likely be handing this off to a parser next).

When working with the InteractiveForm UI element in Web Dynpro, it’s necessary to bind the element’s pdfSource property to a binary context element. From this element, you can read a byte array to obtain the data necessary for the ctx.setPDF() call in the code above. Please see the sample code for examples of how this works.

April 2009 10

Page 16: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

5.1.2 Creating a PDF Dynamically: IWDPDFDocumentCreationContext

Creating a new PDF from raw XML data and an XDP template is similar to the example given above. Int his case, an IWDPDFDocumentCreationContext object is required. This context then requires the raw XML data (as a byte array) and the XDP template (created with LiveCycle Designer, also as a byte array). Once these have been set on the context, the execute method delivers the IWDPDFDocument object:

IWDPDFDocumentHandler hndlr = WDPDFDocumentFactory.getDocumentHandler();

IWDPDFDocumentCreationContext cxt = hndlr.getDocumentCreationContext();

// byte [] containing raw XML data cxt.setData( rawXMLAsByteArray );

// byte [] containing XDP template

// see the next section for tips on loading an existing XDP using

// this call cxt.setTemplate( rawXDLAsByteArray ); … IWDPDFDocument document = context.execute();

5.1.3 Working with Resource Objects Use the WDURLGenerator class to load the XDP contained in your deployed Web Dynpro project.

WDURLGenerator.getResourcePath(wdComponentAPI

.getDeployableObjectPart(), "template.xdp")

The IWDPDFDocumentCreationContext object’s setTemplate() method is overridden to accept a URL or a byte array:

context.setTemplate(WDURLGenerator.getResourcePath(wdComponentAPI

.getDeployableObjectPart(), "template.xdp"));

April 2009 11

Page 17: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

5.2 Document Attachments The PDF specification has provisions for attachments. Attachments in PDFs are very similar to attachments in emails or Microsoft Office documents. The code example provided with this guide shows how an attachment can be added to an existing PDF document using the PDF document API.

Run the example. The first screen contains two file upload controls. Select the PDF example.pdf delivered with the project (in the src/configuration/Components/com.sap.demo.example.attachment.attachmentexample.AttachmentExample directory) using the first file upload control. Select the SAPlogo.gif image contained in the same directory using the second file upload control. Use the Go button to move to the next screen, which renders the uploaded PDF with the image file delivered as an attachment to the PDF. You can view the attachments to the PDF by using the View file attachments button in Adobe Reader.

The attachment is shown in the figure below. You can double-click on the attachment to open it and make sure it was transferred to the server and attached correctly.

The code sample below shows the core logic that attaches the image to the PDF (you could try attaching different files, not just the image). Since we’d like to manipulate an existing PDF in this case, we use the IWDPDFDocumentAccessibleContext interface again. Once the PDF has been set on this context, a new attachment is created and the data from the uploaded file is associated with the attachment. IWDPDFDocument.execute() renders the final result, a PDF with the file attached.

IWDPDFDocumentHandler hndlr = WDPDFDocumentFactory.getDocumentHandler();

IWDPDFDocumentAccessibleContext cxt = hndlr.getDocumentAccessibleContext();

// getByteArray will convert the Resource object to a byte []

cxt.setPDF(getByteArray(pdfResource));

IWDPDFDocumentAttachment attachment = cxt.newAttachment();

attachment.setResource(attachmentResource.read(false));

attachment.setName(attachmentResource.getResourceName());

attachment.setDescription("This is the attachment that you uploaded");

cxt.setAttachment(attachment);

IWDPDFDocument document = cxt.execute();

wdContext.currentContextElement().setPdfSource(document.getPDF());

April 2009 12

Page 18: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

How To Work with Scripts and the PDF Document API in SAP Interactive Forms by Adobe

April 2009 13

6. Appendix

References and Further Reading Code examples that show scripting and the PDF document API

Adobe XML Form Object Model Reference

XDP 2.0 Specification

Web Dynpro JavaDocs for NW 7.1 (CE), including PDF Document API

You will find good examples in your LiveCycle Designer installation directory (C:\Program Files\Adobe\Designer 8.1\EN\Samples), including examples of scripting and table manipulation.

Page 19: How to Work With Scripts and the PDF Document API in SAP Interactive Forms by Adobe

www.sdn.sap.com/irj/sdn/howtoguides