Suche // Search:

30.11.2009

Formulare in bestimmte Verzeichnisse speichern und nach Inhalt aus Formularfeld benennen
//
Save forms to specific directories and named after form field data

Dies Thema hat mich selbst eine lange Zeit beschäftigt.
Wie speichert man ein Formular in ein bestimmtes Vereichnis und wie benennt man es dann auch gleich noch nach einem Feldinhalt aus dem Formular selbst?

Programme wie MS Word können Letzteres ja, nicht so der Adobe Acrobat oder Reader.

Also muss JavaScript wieder her.
Damit klappt's, aber auch nur unter Verwendung von Folder Level Skripten, da die Sicherheitseinstellungen von Acrobat und Reader es ansonsten verbieten.
Eine einfache Variante des Ganzen könnte etwa so aussehen.
Ein Folder Level Script sowie ein Button und Formularfeld im Formular interagieren miteinander.

This issue took a long time for me to clear up.
How can I control the save directory of a form and how do I also rename the form after some data of the form itself?

Applications such as MS Word are able to do the latter, but Adobe Acrobat or Reader don't.

So you need JavaScript to realize this task.
But, because of Acrobat's and Reader's security restrictions this is only possible with folder level scripts.
A simple version can look like this.
The folder level script and also a button and field in the form interact with each other.


Beispiel-Formular – Speicherung in durch Skript angegebene Verzeichnisse
//
Sample form – Saving into directories specified through scripting


Beispiel-Ordner – Speicherung in einer der 4 Unterodner mittels JavaScript möglich
//
Sample folders – Saving directly into one of the 4 subfolder via JavaScript



Folder Level Script – JavaScript

var LCB_SaveAs = app.trustedFunction(function(doc) 
{         
    app.beginPriv();
  var LCB_SaveAsTarget = SaveAsTarget;
  doc.saveAs({cPath: LCB_SaveAsTarget});
    app.endPriv();
});


JavaScript zur Erstellung des Zielpfads
//
JavaScript to create save path 
// Variables we use in the filename taken from fields somewhere in the form
var Var1 = xfa.resolveNode("form1.#subform.cDepartment").rawValue;
var Var2 = xfa.resolveNode("form1.#subform.cName").rawValue;

// Create a time stamp for the new file
var TimeStamp = util.printd("ddmmyyyy", new Date());

// This functions checks the current file name. If it is not the correct file name we don't save the file under a new file name
if (event.target.documentFileName === "LCB_SaveAs_V2.pdf") 
 {
 // Name of a sub directory
 // To save in the same directory enter ""
 // To save in a named subfolder enter "Foldername/" (don't forget the trailing slash!)
 var Directory = Var1 + "/";
 // Concatenate the variables to a file name
 var NewFileName = "LCB_SaveAs_V2" + "_";
 NewFileName += Var2 + "_";
 NewFileName += TimeStamp;
 NewFileName += ".pdf";
 // Replace all characters that are not allowed to be used in a save path – this it to avoid an raise error
 NewFileName = NewFileName.replace(/[\s\!\?\<\>\'\"\*\/\\\=\?\^\`\{\}\|\~]+/g, "_");
 // Concatenate save path with new file name for this form and show it into this field
 this.rawValue = event.target.path.replace(event.target.documentFileName, "") + Directory + NewFileName;
 }
else
 {
 this.rawValue = event.target.path;
 }

JavaScript für Speichern-Button
//
JavaScript for Save Button


if (event.target.documentFileName === "LCB_SaveAs_V2.pdf")
  {
  //A variable for the Folder Level Script
  SaveAsTarget = xfa.resolveNode("form1.#pageSet.Page1.FileParameters.TargetSubDirectory").rawValue; 
  try
   {
   event.target.LCB_SaveAs(event.target);
  
   // Show message to inform the user, where the new file was saved.
   xfa.host.messageBox("File has beed saved under:\r\r" + SaveAsTarget, "File Saved", 3, 0);
   xfa.form.execInitialize();
   }
  catch(e)
   {
   xfa.host.messageBox(e.toString().replace("RaiseError: ","") + "\r\rEnsure the destination folder exists and there isn't already a file with the same file name in that folder!", "Failed to save file", 0, 0);   }
  }
else
  {
  // Open the 'Save As' dialog to let the user choose the target and filename.
  app.execMenuItem("SaveAs");
  }

Das Beispielformular geht noch weiter rein in die Materie und wird sie sicher interessieren.
Sie können z.B. in verschiedene Unterverzeichnisse speicher, je nach dem, welchen Wert Sie aus einer Dropdown-Liste ausgewählt haben.


The example form is much more detailed and will surely find your interest.
For example, you can save the form into one of several sub directories, depending on the selections you made in a drop down list.
Aktualisierung - Eine neuere Version ist hier verfügbar
//
Update - A newer version is available here
http://thelivecycle.blogspot.de/2015/06/save-with-new-name-in-specified.html


26 Kommentare:

  1. Thanks so much for providing this resource! For your example.pdf form, should anything happen when either of the SAVE buttons are selected?

    I have saved the .js file in my javascripts directory for Adobe Reader 9.3

    When I click either SAVE button, nothing happens (there is no file saved with the specified filename)

    AntwortenLöschen
  2. Did you close your Reader after you put the script into the javascript folder?
    It's neccessary to restart Reader.

    AntwortenLöschen
  3. Thanks! Adding usage rights for Reader in Acrobat 9 fixed the issue!

    Now need to figure out how to hide the path field so its not viewable in the form output (ideally)

    AntwortenLöschen
  4. There is a subform "FileParameters" on the masterpage that surrounds those fields. Set its visibility to hidden.

    AntwortenLöschen
  5. I´m a pretty old man without any Java knowledge, but nevertheless I have to amend three pdf forms which have been created in Acrobat 9 with exactly such a "save as" button. Your scripts are giving me a faint idea of what to do, but I don´t know how to let the contents show up in the fields, where to put the field scripts etc.
    You are German, I think, and I´m living in Berlin. Could I pay you for adding "save" buttons to my three (quite primitive) pdf forms?

    AntwortenLöschen
  6. @Jotha

    Tschuldigung, da habe ich wohl Ihren Kommentar übersehen.
    Besteht Ihre Anfrage noch?

    AntwortenLöschen
  7. Hi Radzmar,

    I'm trying to create this for a form on adobe. I'v never written script before. Any chance you can help me with my file ? I would be more then happy to email it to you.

    AntwortenLöschen
  8. @egutie6970

    If this is unknown territory for you I suggest you start with some tutorials on AcrobatUsers.com to get more in touch with JavaScript.

    How to save a PDF with Acrobat JavaScript

    AntwortenLöschen
  9. Hi Radzmar

    First of all, please let me say you Congratulations: I know (because i've been reading
    several posts at acrobatusers) that this is the result of a long and great job.

    I'm working with LC Designer (Acrobat 8.1) on a form which is composed of several subfomrs. Each of them becomes
    "visible" or "hidden" depending on the (raw)value of a dropdown-list.

    When the user finishes filling, the goal is to print the form, changing the name of printed doc depending on the content, in a specific directory, without pop-up confirmation.

    For that reason, when I first saw your script, I though "Hey guy, this is just what I need !"

    I used your folder level script and I put a simplified code inside a buton that calls that script.

    From a "saving as" point of view (after correcting a couple of things), everything works fine.


    But, two issues are still giving me headache:


    The first problem appears with the hidden subforms: they keep hidden at the saved document...Do you have any idea about what is happening? I have been changing the presence of each subform in LC....but nothing new.

    The other issue is that the saved document allows another user to modifing the entire form....I supose that this is because we are saving the document instead of printing it in pdf format.

    In fact, having a printed pdf would be the best way sending the info to our suppliers. Do you think that would it be possible to modify the script to generate a printed pdf (in the same way: no pop-ups, no confimations) instead of saving the form?

    Of course, any suggestion is welcome.
    I look forward to your comments...And I hope you are able to help me.

    JPM

    AntwortenLöschen
  10. @JPM

    Sorry for the late response.
    It's hard to determine, why your subforms are still hidden.
    I need the form to have a clue whats going on.

    And yes, the best method to flatten your forms is to print them via PDF Printer (Distiller).
    Any way, I don't know a method how to deliver a value from the form over to Distiller to generate a different file name for each print.

    Alternatively you could use a loop to lock down all your form fields before saving them through the folder level script.

    JavaScript to lock all fields:
    for (var p = 0; p < xfa.host.numPages; p++)
    {
    var oFields = xfa.layout.pageContent(p, "field");
    for (var f = 0; f < oFields.length; f++)
    {
    var field = oFields.item(f);
    // Protect field against changes
    field.access = "readOnly";
    }
    }

    Hope this helps

    AntwortenLöschen
  11. Hi radzmar,
    I am glad to see elaborated and clear discussion on this topics. I was trying export as xml in specific folder on acrobat X pro 10. following script was being used:

    function myDateString()
    {

    return util.printd("mmddyy_HHMMss", new Date());

    }

    // SaveAs Function
    var mySaveDoc = app.trustedFunction(function(doc) {

    app.beginPriv();
    var myPath = "/C/Users/Dream_peak/Desktop/test"+"/"+ myDateString() + ".xml";

    doc.exportXFAData(myPath);
    app.endPriv();

    });

    Nothing happen. What should I do?

    Your sample is working fine but when I change .pdf to .xml and doc.saveAs to doc.exportXFAData, it is shoeing security error.

    Would you help me?

    Thanks

    AntwortenLöschen
  12. Hi,

    the exportXFAData function requieres a few more parameters.
    This sample will export the currents file Data as XML file into the same directory.
    Other directories will also work, but Acrobat will restrict access to system critical folders by default and will return an Not allowed exception in the JS Console (can be opened with ctrl + J).

    function myDateString() {
    return util.printd("mmddyy_HHMMss", new Date());
    }
    // SaveAs Function
    var mySaveDoc = app.trustedFunction(function(doc) {
    app.beginPriv();
    var myPath = this.path.replace(this.documentFileName, "");
    var myPath = myPath + "TEST_" + myDateString() + ".xml";
    this.exportXFAData({
    cPath: myPath,
    bXDP: false,
    aPackets: ["*"]
    })
    app.endPriv();
    });

    AntwortenLöschen
  13. Oh great!!!

    Thanks a lot.

    AntwortenLöschen
  14. I am trying to save just the xdp data from a form in the browser. Do folder level scripts work when the pdf is displayed using reader in the browser?

    AntwortenLöschen
  15. When you open the sample form in a browser window, and all fields get populated with the path or file names, then you already have access to the folder level script and can use it also to save forms.

    The problem now is that the paths are displayed in the URI format such as "file:///D:/FORMS/" instead of "/D/FORMS/".

    When you try to use save paths in this format the saveAs script will fail with an exception "UnsupportedValueError: Value is unsupported. ===> Parameter cPath" because the saveAs function doesn't support path in the URI format.

    To get rid of this you can use a regular expression to reformat the path in the scheme you need.

    Here an example to save in the current directory:

    var Var1 = xfa.resolveNode("form1.#subform.cDepartment").rawValue;
    var Var2 = xfa.resolveNode("form1.#subform.cName").rawValue;
    var TimeStamp = util.printd("ddmmyyyy", new Date());

    if (event.target.documentFileName === "LCB_SaveAs_V2.pdf") {
    var NewFileName = "LCB_SaveAs_V2" + "_";
    NewFileName += Var1 + "_";
    NewFileName += Var2 + "_";
    NewFileName += TimeStamp;
    NewFileName += ".pdf";
    NewFileName = NewFileName.replace(/[\s\!\?\<\>\'\"\*\/\\\=\?\^\`\{\}\|\~]+/g, "_");

    var newSavePath = event.target.path.replace(event.target.documentFileName, "") + NewFileName;
    this.rawValue = newSavePath.replace(/(file)|\:|\||\/{2}/gi ,"");
    } else {
    this.rawValue = event.target.path;
    }

    AntwortenLöschen
  16. Hi radzmar,

    I have got a problem. Following script is working fine in Acrobat pro but not work for reader.

    var mySaveDoc = app.trustedFunction(function(doc)
    {
    app.beginPriv();
    var myPath = this.path.replace(this.documentFileName, "");
    var fm_SaveAsTarget = SaveAsTarget;
    var myPath = myPath + fm_SaveAsTarget + ".xml";
    this.exportXFAData({
    cPath: myPath,
    bXDP: false,
    aPackets: ["*"]
    }
    )
    app.endPriv();
    }
    );


    var pdf_SaveAs = app.trustedFunction(function(doc)
    {
    app.beginPriv();
    var myPath = this.path.replace(this.documentFileName, "");
    var pdf_SaveAsTarget = PDFSaveAsTarget;
    var myPath = myPath + pdf_SaveAsTarget + ".pdf";
    doc.saveAs({cPath: myPath});
    app.endPriv();
    });

    Would you tell me what I should do? I have enabled reader right extension with acrobat pro.

    Thanks for your time.

    AntwortenLöschen
  17. Hi,

    sorry for the delay, I've been away a couple of days!

    To use exportXFAData() with Reader, the form needs the so called exports form rights.
    The usage rights you can apply through Acrobat do not enable the neccessary export rights, this can only be done with LiveCycle Reader Extensions products.

    AntwortenLöschen
  18. Dear Radzmar,

    Thanks for your great sample.

    All save location works perfect in my PC except "My Documents"
    When I click on Save button Save as window open with current file name "LCB_SaveAs_V2.pdf". file name does not generate from cName & cDepartment.
    I'm using windows.

    Please can you help me to fix this problem.

    Regards,
    Ebnul

    AntwortenLöschen
  19. Hi Ebnul,

    I found the root of all evil in my sample.

    Firstly the script in the field "SaveAsMyDocuments" needs an additional line of code.

    ...
    if (event.target.documentFileName === "LCB_SaveAs_V2.pdf") {
    var newPath = MyDocumentsPath.rawValue.replace(event.target.documentFileName, "");
    newPath += "/" // this is the added code line
    newPath += "LCB_SaveAs_V2"
    ...


    Secondly, the related save button checks the file name "LCB_SaveAs.pdf" instead of "LCB_SaveAs_V2.pdf", so you need to change that script too.

    Best,
    Radzmar

    AntwortenLöschen
  20. Dear Radzmar,

    I found this very helpful. The link to the sample ZIP file does not sem to work. Is there anotherlocation where I could download it?

    Kind Regards
    Martin

    AntwortenLöschen
  21. Hi Martin,

    I've updated the link, so is now working again.

    AntwortenLöschen
  22. Hi radzmar,
    Some pdf files i can edit but after only saved.
    Because i want to read

    Thanks
    Subash

    AntwortenLöschen
    Antworten
    1. Sorry Subash, but I don't understand your request. Please provide more details of what you're trying to do.

      Löschen
  23. dear Radzmar,
    how can i create on uppercase on the names field and all file.

    thx

    sivanesh

    AntwortenLöschen
  24. Hi,

    you can add the toUpperCase() method to the fields script in the layout:ready event.

    For the field TargetCurrentDirectory replace the current script with the following script:

    // Variables we use in the filename taken from fields somewhere in the form
    var Var1 = xfa.resolveNode("form1.#subform.cDepartment").rawValue;
    var Var2 = xfa.resolveNode("form1.#subform.cName").rawValue;

    // Create a time stamp for the new file
    var TimeStamp = util.printd("ddmmyyyy", new Date());

    // This functions checks the current file name. If it is not the correct file name we don't save the file under a new file name
    if (event.target.documentFileName === "LCB_SaveAs_V2.pdf") {
    // Concatenate the variables to a file name
    var NewFileName = "LCB_SaveAs_V2" + "_";
    NewFileName += Var1 + "_";
    NewFileName += Var2 + "_";
    NewFileName += TimeStamp;
    NewFileName += ".pdf";
    // Replace all characters that are not allowed to be used in a save path – this it to avoid an raise error
    NewFileName = NewFileName.replace(/[\s\!\?\<\>\'\"\*\/\\\=\?\^\`\{\}\|\~]+/g, "_").toUpperCase();
    // Concatenate save path with new file name for this form and show it into this field
    this.rawValue = event.target.path.replace(event.target.documentFileName, "").toUpperCase() + NewFileName;
    } else {
    this.rawValue = event.target.path.toUpperCase();
    }

    The field now will display all paths in uppercase.

    AntwortenLöschen
  25. Really cool post, highly informative and professionally written and I am glad to be a visitor of this perfect blog, thank you for this rare info!
    Regards adobe cq5 training in hyderabad

    AntwortenLöschen