Form Javascript: attachment is undefined
Copy link to clipboard
Copied
for (var i = 0; i < this.dataObjects.length; i++) {
console.println(this.dataObjects[i].name);
}
// Open the attached PDF file
this.exportDataObject({ cName: "test.pdf", nLaunch: 2 });
// Get the field values from the form
var value1 = this.getField("Employee First Name Field").valueAsString;
var value2 = this.getField("Employee Last Name Field").valueAsString;
// Set the field values in the attached PDF
var attachment = this.dataObjects["test.pdf"];
if (attachment) {
attachment.extractPages();
var pages = attachment.getPageNumWords();
for (var i = 0; i < pages.length; i++) {
var fields = pages[i].getNthFieldName();
for (var j = 0; j < fields.length; j++) {
if (fields[j] == "field1") {
pages[i].setField("field1", value1);
}
if (fields[j] == "field2") {
pages[i].setField("field2", value2);
}
}
}
// Save and close the attached PDF
attachment.saveAs("Attachment_autofilled.pdf");
attachment.closeDoc(true);
} else {
console.println("Attachment not found!");
}
Writing a code to export field values from one pdf to an attached pdf at the click of a button.
My code opens the attachment, but throws up the error "attachment is undefined". The var attachment is declared. The name is written correctly. The attachment is visible in the Attachments sidebar.
for (var i = 0; i < this.dataObjects.length; i++) { console.println(this.dataObjects[i].name); } this returns exactly the attachment name. The fieldnames i'm exporting from and to both exist and are written correctly.
Any ideas why this is happening?
Copy link to clipboard
Copied
The "doc.dataObjects" property is an array listing the names and information for the attached files. It is not the actual file.
Exporting the data object doesn't help in this context. It may open the attached PDF in Acrobat, but this action does not provide the doc object for it.
Also, extracting pages does nothing to help with this process. Remove that code.
The correct way to get the document object for an attached PDF, is to call "doc.openDataObject()".
Use the Acrobat JavaScript Reference early and often

