Java Script to save as PDF with password...

Hi people.  My goal is to have a script to perform the following functions:

1. Enter the name of the active document

2 Save as PDF using the active doc name with password lock in the same directory the *.ai file is located

I started to play with the code, but I don't know what I'm doing... newbie.

Here's the code that I currently use.

var curDoc = app.activeDocument;
var destFolder, sourceFolder, files, fileType, sourceDoc, targetFile, pdfSaveOpts;
//var destName = "~/Desktop/Testpassword1.pdf";
var destName = targetFile
saveFileToPDF(destName);
//sourceFolder = Folder.selectDialog( 'Select the folder with Illustrator files you want to convert to PDF', '~' );
//saveFileToPDF(destName);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if ( sourceFolder != null )
{
    //files = new Array();
    //fileType = '*.ai';
    //fileType = prompt( 'Select type of Illustrator files to you want to process. Eg: *.ai', ' ' );
    
    // Get all files matching the pattern
    //files = sourceFolder.getFiles( fileType );
    
    if ( files.length > 0 )
    {
        // Get the destination to save the files
        destFolder = Folder.selectDialog( 'Select the folder where you want to save the converted PDF files.', '~' );
        for ( i = 0; i < files.length; i++ )
        {
            sourceDoc = app.open(files[i]); // returns the document object
                                    
            // Call function getNewName to get the name and file to save the pdf
            targetFile = getNewName();
            
            // Call function getPDFOptions get the PDFSaveOptions for the files
            //pdfSaveOpts = getPDFOptions( );
            
            // Save as pdf
            sourceDoc.saveAs( targetFile, pdfSaveOpts );
            
            sourceDoc.close();
        }
        alert( 'Saved' + destFolder );
    }
    else
    {
        alert( 'No matching files found' );
    }
}
 ///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 function getNewName()
{
    var ext, docName, newName, saveInFile, docName;
    docName = sourceDoc.name;
    ext = '.pdf'; // new extension for pdf file
    newName = "";
        
    for ( var i = 0 ; docName[i] != "." ; i++ )
    {
        newName += docName[i];
    }
    newName += ext; // full pdf name of the file
    
    // Create a file object to save the pdf
    saveInFile = new File( destFolder + '/' + newName );
    

    return saveInFile;
}
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function saveFileToPDF (dest) {

var doc = app.activeDocument;

if ( app.documents.length > 0 ) {

var saveName = new File ( dest );
saveOpts = new PDFSaveOptions();
saveOpts.compatibility = PDFCompatibility.ACROBAT5;
saveOpts.generateThumbnails = true;
saveOpts.optimization = true;
saveOpts.preserveEditability = true;
saveOpts.bleedOffsetRect = [2,2,2,2];
saveOpts.trimMarks = true;
//=======================  COMPRESSION ===========================
saveOpts.colorCompression = CompressionQuality.JPEGMAXIMUM;
saveOpts.colorDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
saveOpts.colorDownsampling = 300;
saveOpts.colorDownsamplingImageThreshold = 450;
//-----------------------------------------------------------------------------------------------------------
saveOpts.grayscaleCompression = CompressionQuality.JPEGMAXIMUM;
saveOpts.grayscaleDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
saveOpts.grayscaleDownsampling = 300;
saveOpts.grayscaleDownsamplingImageThreshold = 450;
//-----------------------------------------------------------------------------------------------------------
saveOpts.monochromeCompression = MonochromeCompression.CCIT4;
saveOpts.monochromeDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
saveOpts.monochromeDownsampling = 1200;
saveOpts.monochromeDownsamplingImageThreshold = 1800;
//====================  END OF COMPRESSION =======================
saveOpts.colorConversionID = ColorConversion.COLORCONVERSIONREPURPOSE;
saveOpts.colorDestinationID = ColorDestination.COLORDESTINATIONWORKINGCMYK;
///
saveOpts = new PDFSaveOptions();
saveOpts.requirePermissionPassword = true;
saveOpts.permissionPassword = "pink";
saveOpts.pDFAllowPrinting = PDFPrintAllowedEnum.PRINT128LOWRESOLUTION;
doc.saveAs( saveName, saveOpts );
}
}

It takes a lot of work.

too many errors with the code list.

It should be re written from scratch.

This gives a bash.

//---------------------------------------------------
//          Save as LOCKED pdf
//---------------------------------------------------
//
//          Qwertyfly
//          03/07/2015
//          Version 1.0
//
//---------------------------------------------------
//
//          Set your password here
var pass = 'pink';
//
//---------------------------------------------------
if ( app.documents.length > 0 ) {       //make sure we have a file open to work with
    var doc = app.activeDocument;
    if ( doc.fullName.toString().substr(doc.fullName.toString().lastIndexOf('.')) == ".ai" ){       //Make sure your working with an ai file
        var myFile = new File(doc.fullName.toString().substr(0,doc.fullName.toString().lastIndexOf('.')) + ".pdf");
        var saveOpts;
        setSaveOptions();
        saveFileToPDF(myFile);
    }else{alert("Active Document is not an '.ai' file")}
}else{alert("No Document Open")}

function saveFileToPDF(myFile){
    var originalInteractionLevel = userInteractionLevel;        //save the current user interaction level
    userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;      //Set user interaction level to suppress alerts
    doc.saveAs(myFile,saveOpts);        //Save File
    userInteractionLevel = originalInteractionLevel;        //Set user interaction level back to original settings
}

function setSaveOptions(){
    //  Setup Save Options
    saveOpts = new PDFSaveOptions();
    saveOpts.compatibility = PDFCompatibility.ACROBAT5;
    saveOpts.generateThumbnails = true;
    saveOpts.optimization = true;
    saveOpts.preserveEditability = true;
    saveOpts.bleedOffsetRect = [2,2,2,2];
    saveOpts.trimMarks = true;
    //=======================  COMPRESSION ===========================
    saveOpts.colorCompression = CompressionQuality.JPEGMAXIMUM;
    saveOpts.colorDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
    saveOpts.colorDownsampling = 300;
    saveOpts.colorDownsamplingImageThreshold = 450;
    //-----------------------------------------------------------------------------------------------------------
    saveOpts.grayscaleCompression = CompressionQuality.JPEGMAXIMUM;
    saveOpts.grayscaleDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
    saveOpts.grayscaleDownsampling = 300;
    saveOpts.grayscaleDownsamplingImageThreshold = 450;
    //-----------------------------------------------------------------------------------------------------------
    saveOpts.monochromeCompression = MonochromeCompression.CCIT4;
    saveOpts.monochromeDownsamplingMethod = DownsampleMethod.BICUBICDOWNSAMPLE;
    saveOpts.monochromeDownsampling = 1200;
    saveOpts.monochromeDownsamplingImageThreshold = 1800;
    //====================  END OF COMPRESSION =======================
    saveOpts.colorConversionID = ColorConversion.COLORCONVERSIONREPURPOSE;
    saveOpts.colorDestinationID = ColorDestination.COLORDESTINATIONWORKINGCMYK;
    ///
    saveOpts.requirePermissionPassword = true;
    saveOpts.permissionPassword = pass;
    saveOpts.pDFAllowPrinting = PDFPrintAllowedEnum.PRINT128LOWRESOLUTION;
}

Tags: Illustrator

Similar Questions

  • How can save a PDF with password

    How can save a PDF with password

    Hi MacUser2,

    Trial is for 30 days.

    Once the trial is over you will be able to open PDF files by using the password that you have installed.

    Kind regards
    Nicos

  • which API allows to save the PDF with Adobe Reader 9?

    Hello

    which API allows to save the PDF with Adobe Reader 9? It is said that "CosDocSaveWithParams" may not be used.

    Thank you!

    Jimmy

    I've personally used both in the drive in a plugin, and the drive itself makes these calls.  HOWEVER, they only work on the active Reader documents.

  • Can you help me to insert a JAVA script into an Adobe PDF form I created.

    I have never programmed in Java and need a Java script to insert in a calculation field in an Adobe PDF form that I created using Adobe Acrobat Pro DC.  This form will be the one that can be filled on the PC or printed and filled out manually.  The calculated field will display a zero unwanted when printing and I want it to be empty.  Another field will be a calculated percentage and displays an error when there is no divider; a similar problem, I want to be a Virgin and the person filing the form manually to calculate the field and write.  I don't have time to learn

    The Excel formula would be: If (Cell_1A = "", "", Cell_1A + Cell_1B)

    What would be the JAVA script in a dialog box "Simplified field Notation" or "custom calculation Script?

    Both of these things require a custom calculation. For the script of the division, you can use something like this:

    var a = Number(this.getField("Field A").value);
    var b = Number(this.getField("Field B").value);
    if (b==0) event.value = "";
    else event.value = a/b;
    

    For the conditional script, you can use this:

    var a = this.getField("Cell_1A").valueAsString;
    var b = this.getField("Cell_1B").valueAsString;
    if (a=="") event.value = "";
    else event.value = Number(a)+Number(b);
    
  • Script to save as tif with compression zip, file properties

    I don't know anything about scripting so that I cannot understand the answers to similar questions and merge a response to mine.

    I'm looking for a script to save my images as tiff with zip compression using the title of the Document in the file properties.

    I want to assign it to a button to save me time, images of scanning takes enough time as it is

    Thanks in advance for any help.

    If the file exists, this will add the time so it will be a different file name.

    
    

    #target photoshop;

    main();

    main() {} function

    var Path = Folder("/D/Scanned");

    If (!.) Path.Exists) {}

    Alert (path + "does not exist!");

    return;

    }

    var fileName = activeDocument.info.title;

    if(FileName == '') {}

    Alert ("there is no title in the present document);

    return;

    }

    var saveFile = file (path + "/" + name + ".tif");

    If (SaveFile.Exists) saveFile = file (path + "/" + fileName + "-" + time() + ".tif");

    SaveTIFF (saveFile);

    app.activeDocument.close (SaveOptions.DONOTSAVECHANGES);

    };

    function SaveTIFF (saveFile) {}

    tiffSaveOptions = new TiffSaveOptions();

    tiffSaveOptions.embedColorProfile = true;

    tiffSaveOptions.alphaChannels = true;

    tiffSaveOptions.layers = true;

    tiffSaveOptions.imageCompression = TIFFEncoding.TIFFZIP;

    activeDocument.saveAs (saveFile, tiffSaveOptions, true, Extension.LOWERCASE);

    };

    time() {} function

    var date = new Date();

    var d = date.getDate ();

    var day = (d< 10)="" '0'="" +="" d="" :="">

    var m = date.getMonth () + 1;

    var month = (m< 10)="" '0'="" +="" m="" :="">

    yy var = date.getYear ();

    var year = (yy< 1000)="" yy="" +="" 1900="" :="">

    var digital = new Date();

    var h = digital.getHours ();

    var minutes = digital.getMinutes ();

    var seconds = digital.getSeconds ();

    var amOrPm = "AM";

    If (hours > 11) amOrPm = 'H ';

    If (hours > 12 hours) = UH - 12.

    If (hours == 0) hours = 12;

    If (minutes<= 9)="" minutes="0" +="">

    If (seconds<= 9)="" seconds="0" +="">

    todaysDate = hours + "-" + minutes + "-" + seconds + amOrPm;

    Return todaysDate.toString ();

    };

  • I can't save a PDF with the same name

    I can't save pdf files with the same name on the network drive in our society. I have full control over this network drive and can do anything create/read/write/change. Other programs work fine, but not Adobe Reader. I can save a pdf file with a different name, but when I try to save as in XI or replace as in DC had an error: the file is read-only or opened by someone else. Save the document under a different name or in a different folder.

    By the way, Acrobat Pro, I got the same message.

    reader_error.png

    Hi igorp74028164,

    Please provide the exact point of the software & OS installed on your system. Also check if it is there any update available for the software after crossing "" help > check updates "»

    Follow this thread to reset the preferences for the acrobat software. : - How to reset preference settings in Acrobat format.

    Also please check if this file is saved to the network drive or local, if its network on Please save it on local disk & then check. Make sure also that this preview pane must be closed in windows Explorer.

    Kind regards

    Christian

  • Save a PDF with Adobe Reader

    I'm sure there's a way to save your PDF file once you complete the form using Adobe Reader. From my understanding, I need to activate Adobe Reader Extention, but I don't know how to do this. If this is correct, can someone please explain how to do this? Thank you!

    Yes, it is because you do not have Acrobat X.

    Is Acrobat 9 I think.

    Then, the option is located under the tool menu.

  • Scripting 'Save PSD to PDF with password security' and 'Open a PDF file with password security' issue.

    Hello!

    I am now building an extension for Photoshop. The script (jsx) should save the document as Photoshop PDF secured with a password. The IPL is the same all the time and is defined in the script. Then, the script is to open the PDF file with that same password. I need this to protect the PDF of the opening by a user, so that only the script has access to the file.

    I googled a lot. I saw a similar topic on this community date in 2012. He did not respond. With one comment saying that savings with a password appears to be possible via GUI and not a script.

    Nothing has changed since 2012?

    P.S. .requireDocumentPassword and Illustrator .documentPassword do not work in PS and ScriptListener gives still nothing :-/

    ScriptListener always gives nothing

    Which probably means the task is not (yet) possible to achieve with Photoshop scripts.

    The Photoshop DOM and I seem to have weaknesses or omissions that I consider more relevant, but if you consider the matter as essential you can post a feature request to

    Community customer Photoshop family

  • Editing of PDF with password

    I have a PDF form with 3 different sections to be completed by 3 different people (1 person fills their section, it automatically sends to anyone, etc. 2) I don't want these people to change/complete the forms in their own section, is it possible? Better protection of password for each individual article?

    It is not possible. There is no way to provide different security for different parts of a PDF form.

    Once a PDF file is opened, everyone who has access has the same privileges.

  • Book of attachment pdf with password

    Hi all



    I have a requirement, as then to provide a PDF via the ibot, it should be password protected. The end-user needs to open it with a password. any help will be appreciated.


    Thank you.

    Hello

    It can be done with the BI Publisher (published reporting). IN the RTF to word builder model select Properties, and then in the custom tab, you have the possibility of a password hardcoded and a dynamic password which is fed to it by XML feed (report output)

    Note: the editor of BI manual has the details for this.

    -Karine

  • Java script app and syntex error with Firefox 17... can not solve it

    Since I downloaded Firefox 17 I get the above error.

    This problem may be caused by an extension that is not working properly.

    Start Firefox in Safe Mode to check if one of the extensions (Firefox/tools > Modules > Extensions) or if hardware acceleration is the cause of the problem (switch to the DEFAULT theme: Firefox/tools > Modules > appearance).

    • Do not click on the reset button on the start safe mode window or make changes.
  • Cannot save PDF with CD player?

    I'm unable to save any PDF with CD player. The economy icon is removed, and CTRL S does nothing.  Any ideas?

    Is that what you have made changes in registered pdf format previously? If this isn't the case, as Bernd said, Save... as the first. Then, when you make changes, you can use Save.

  • How to save a PDF file with zoom as TIFF/PNG of quality equal?

    I have a graphic photographic resolution in PDF (vector graphics). Zoom in Acrobat results in an impeccable oversampled image you expect from vector graphics. However, I can not save the PDF upscale as an oversampled TIFF or PNG - I get horrible artifacts. How can I get Acrobat to save the PDF with zoom a PNG/TIFF image?

    Thank you very much...

    You can get what you want with instant tool under editing, AA XI. This will give you a screenshot of what is shown on the screen. The best way is to open the vector graphic in Illustrator and work directly with vector illustration.

  • Why do I get a blank screen when I try to save a pdf document?

    When I try to "save under", a PDF, I get an empty bubble.  How can I fix it?

    So if I get this right, the issue seems to be specific to a secure PDF (PDF with password). If you are in a business/office environment, perhaps the administrator has installed any tool or plugin to prevent registration of PDF files secure?

    A few things to try (if you haven't already done so):

    1. reboot the computer

    2 uninstall Acrobat, run the tool AcroCleaner, Download Adobe Reader and Acrobat cleaning - Adobe Labs tool, and then reinstall Acrobat.

  • JavaScript to invite the user to save in PDF format

    I make the changes with the code for the file. I want the user to be prompted to save as a file .ai first. I have that down. Now, I'm eager to have the user immediately prompted to save as pdf with only the option optimize for fast web view selected. I think it's an adobe built-in smallest file size.

    The reason for wanting the guest is because I want to save the files in 2 different places.

    Here is my code so far...

    var doc = app.activeDocument;
    // Save as .ai file  
    var fileName = doc.fullName;  
    var thisFile = new File(fileName);
    var saveFile = thisFile.saveDlg();
    doc.saveAs (saveFile);
    
    
    // Save as .pdf file
    var pdfSaveOptions = new PDFSaveOptions();  
    pdfSaveOptions.pDFXStandard=PDFXStandard.PDFXNONE;  
    pdfSaveOptions.compatibility = PDFCompatibility.ACROBAT5;  
    pdfSaveOptions.preserveEditability = false;  
      
    var pdfFile = new File(fileName);  
    doc.saveAs(pdfFile, pdfSaveOptions);
    
    
    
    

    HAVE CS4 Windows 7 64 bit

    the folder structure is already existing?

    If so, things are simple.

    If the name and the number are in the file you could draw that from the entry rather then manual doc to guests.

    (Note that there is no test to check the folders exist etc...)

    var job = prompt("Enter Job Name");
    var num = prompt("Enter Job Number");
    aiFile = "D:\\"+job+"\\"+num+"\\AI\\Schematic.ai"
    pdfFile = "D:\\"+job+"\\"+num+"\\PDF\\Schematic.pdf"
    
    var newaiFile = new File(aiFile);
    var doc = app.activeDocument;
    doc.saveAs (newaiFile);
    
    var pdfOpts = new PDFSaveOptions();
    pdfOpts.pDFXStandard=PDFXStandard.PDFXNONE;
    pdfOpts.compatibility = PDFCompatibility.ACROBAT5;
    pdfOpts.preserveEditability = false;
    var newpdfFile = new File(pdfFile);
    doc.saveAs(newpdfFile, pdfOpts);
    

    If you want the script to create the folders so it is a little more difficult.

    JavaScript will not do that, and you need another work autour.

    something like that...

    if (Folder(qfolder).exists){
    app.activeDocument.saveAs( saveName, saveOpts );
    }else{
               //alert("about to try bat");
               batpath= 'call "C:\\Adobe Scripts\\MakeDirectory.bat"';
                battemp = new File("C:\\Adobe Scripts\\tempBAT.bat");
                battemp.open("w");
                battemp.writeln(batpath + " " + qfolder);
                battemp.close();
                battemp.execute();
             //alert("Had to Create Folder, Please press OK to continue...");
                $.setTimeout = function(func, time) {
                        $.sleep(time);
                        func();
                };
             $.setTimeout(function(){ app.activeDocument.saveAs( saveName, saveOpts )},200);
             }
    }
    

    the MakeDirectory.bat is just:

    ECHO OFF
    CLS
    
    IF %1=="" GOTO BLANK
    
    SET savepath=%*
    MKDIR %savepath%
    GOTO FINISH
    
    :Blank
    ECHO No Folder provided
    GOTO FINISH
    
    :FINISH
    

    the tempBat.bat is used to call the MakeDirectory.bat with the name of the file as an argument.

Maybe you are looking for