Acrobat Javascript: Error referencing document.
Hi all.
I am trying to debug some code I have for moving/resizing pages. Granted, I'm familiar with coding but not Acrobat Specific API. And I'm also having trouble finding simple documentation about what functions are available (eg every function available for this.*).
Can I have some insight on where I'm going wrong below? It won't run and gives me errors both about functions I'm calling not existing, as well as my calls to try and get a handle to the current document.
// Display initial dialog box
app.alert("The script is running. Another dialog box will show upon completion.", 1);
// Function to move page content left and resize page if necessary
function adjustPage(page) {
// Define margins
var rightMargin = 0.4 * 72; // 0.4 inch in points
var leftMargin = 0.2 * 72; // 0.2 inch in points
// Get page width
var pageWidth = page.getCropBox()[2] - page.getCropBox()[0];
// Iterate through page contents
var contents = page.pageContents;
for (var i = 0; i < contents.length; i++) {
var content = contents[i];
if (content instanceof TextAnnotation) {
// Move text annotations
content.move([-rightMargin, 0]);
} else {
// Move other content
content.move([-rightMargin, 0]);
}
}
// Check if any content is outside right margin
var pageBounds = page.getPageBox();
if (pageBounds[2] > pageWidth - rightMargin) {
// Resize page
var resizeAmount = pageBounds[2] - (pageWidth - rightMargin);
page.setSize(pageWidth - resizeAmount, pageBounds[3]);
}
// Check if any content is outside left margin
pageBounds = page.getPageBox();
if (pageBounds[0] < leftMargin) {
// Resize page
var resizeAmount = leftMargin - pageBounds[0];
page.setSize(pageWidth + resizeAmount, pageBounds[3]);
}
}
// Get the current document
var doc = app.activeDocs[0];
// Set the document to edit mode
if (!doc.isDocumentEdited) {
doc.dirty = true;
}
// Initialize error log
var errorLog = [];
// Iterate through pages
for (var i = 0; i < doc.numPages; i++) {
var page = doc.getPageNth(i);
if ((i + 1) % 2 === 0) { // Check if page is even
adjustPage(page);
}
}
// Save error log to CSV file
var errorLogStr = "Error,Page Number\n";
for (var i = 0; i < errorLog.length; i++) {
errorLogStr += errorLog[i].error + "," + errorLog[i].pageNumber + "\n";
}
var filePath = doc.path.replace(/\.pdf$/, "-Script-Errors.csv");
try {
var file = util.writeFile(filePath, errorLogStr);
if (file != null) {
// Open error log file
app.openDoc(file.path);
} else {
app.alert("Error saving error log file.");
}
} catch (e) {
app.alert("Error saving error log file: " + e);
}
// Display completion dialog box
app.alert("Script completed. Error log saved to: " + filePath, 1);
