Skip to main content
jelux
Participating Frequently
May 27, 2022
Answered

export PDF business cards sequentially

  • May 27, 2022
  • 3 replies
  • 1229 views

hi I wanted to ask if there is a scrip to export pdfs created with the data merge utility, let me explain, I created a file with 100 pages inside, all of business cards with different names, one front and one back, then 50 sides and 50 back, the customer asks me to export a pdf file for each name then 50 pdf files, how can I export the pdf in pairs two by two? thank you very much

This topic has been closed for replies.
Correct answer Mike Bro

Hello @jelux.

Sorry for the delayed response...

Re: "I'm not very familiar with scripts so I don't know how to connect the names as well it would be nice to be able to export the pdf files with their names

any suggestions ?"

 

Give this a try...

1. Start off by creating a Paragraph style named "PDF_name"

2. Create a text box and assign the Paragraph style "PDF_name"

3. Assign the field from the data source for the pdf naming

4. Create and save the Merged document, run the script to export the pdfs


The below script will export pdfs named by the contents of the text box useing the Paragraph style named "PDF_name".

   var doc = app.documents[0];
   var export_preset = app.pdfExportPresets.item("[High Quality Print]");

   var myResult = {};
   var allStoriesArray = app.documents[0].stories.everyItem().getElements();
   
    for(var n=0; n<allStoriesArray.length; n++){
    var currentStory =  allStoriesArray[n];
    var textContainersLength = currentStory.textContainers.length;
    var lastFrameOfStory = currentStory.textContainers[textContainersLength-1];
    var objToCheck = lastFrameOfStory;
    
    if(lastFrameOfStory.constructor.name == "TextPath")
    objToCheck = lastFrameOfStory.parent
    
    if(currentStory.overflows && objToCheck.itemLayer.visible && objToCheck.parentPage != null)
    myResult[objToCheck.parentPage.name] = objToCheck.parentPage.name;
    }
    
    var pageList = new Array;
    for(var a in myResult)
    pageList.push(a);
        
    pageList.sort(function(a,b) {return a-b});
    
    if(pageList.length > 0){
    alert("Error!\nDocument contains overset text on page(s): \r" + pageList);
    exit();
    }
    
var myPages = [];
for (var i=0; i<doc.pages.length; i ++) {
 myPages.push(app.activeDocument.pages[i].name);
}

// Function Returns "oddPages"
var myPageNums = (myPages);
var oddPages = [];

var oddNumbers = function(myPageNums) {
for (var i = 0; i < myPageNums.length; i++) {

   if ((myPageNums[i] % 2) ==1) {
    oddPages.push(myPageNums[i]);      
   }
  }
}
oddNumbers(myPageNums);


       //Function Returns pdf_name for Selected Pages
      function getTextFromPageUsingParagraphStyle(myPage){
     
     if (doc.paragraphStyles.itemByName("PDF_name") == null) {
      alert ('Error!\nThe Paragraph Style "PDF_name" does not exist or is Labeled Incorrectly.');
      exit();
}
          app.findTextPreferences = app.changeTextPreferences = null;   
          app.findTextPreferences.appliedParagraphStyle = "PDF_name";  
  
          var myTextframes = myPage.textFrames;  
          var pdf_name = null;
          
          for (y=0; y < myTextframes.length; y++){  
                var mySearchResult = myTextframes[y].findText();  
                if (mySearchResult.length > 0){  
                pdf_name = mySearchResult[0].contents; 
                 break;  
                }  
          } 
      
         return pdf_name;      
} 

//Dialog/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var mySelectedFolder = Folder.selectDialog ("Select a Folder");
if(mySelectedFolder  != null){

}else{
    alert ("Canceled!");
    exit();
}

var myDialog = app.dialogs.add({name:"DataMerge 2-Page HR Pdf Exporter", canCancel:true});
with (myDialog){
with (dialogColumns.add()){

with (dialogRows.add())
staticTexts.add({staticLabel:"Page Range Options", minWidth:25});
with (borderPanels.add()){
var myradiogroup1 = radiobuttonGroups.add();
with (myradiogroup1){
var myyesradiobutton1 = radiobuttonControls.add({staticLabel:'Export All Pages', checkedState:true});
var mynoradiobutton1 = radiobuttonControls.add({staticLabel:'Export Select Pages'});    
staticTexts.add({staticLabel:"", minWidth:75});  
}
}
}
}
if (myDialog.show() == true){

var SelectedPages = myradiogroup1.selectedButton; 

}else{
}
myDialog.destroy();

//All Pages//////////////////////////////////////////////////////////////////////////////////////////////////

 if (SelectedPages == false){
     
  for(var p = 0; p < app.documents[0].pages.length; p=p+2) {  
    var frames = app.documents[0].pages[p].textFrames;  
    var pdf_name = null;  
 
    for(i = 0; i < frames.length; i++) {
     try {
       if(frames[i].paragraphs[0].appliedParagraphStyle.name == 'PDF_name') {  
          pdf_name = frames[i].paragraphs[0].contents;  
          break;
          }  
       }catch (e){
     }
  }

     
    if (pdf_name == null) { 
    alert ('Error!\nThe Paragraph Style "PDF_name" is not applied to one or more of the pages or is Labeled Incorrectly.');
    exit();
    }
      
      if(pdf_name != null) {  
 
    }    

app.scriptPreferences.enableRedraw = false;  
w = new Window('window', 'Exporting Pdfs');  
pb = w.add('progressbar', [12, 24, 375, 36], 0, 100);  
w.show();  
for (i = 0; i < 100; i++){  
  pb.value = i;  
  w.update();  
  $.sleep(10);  
}  
w.close();

app.pdfExportPreferences.pageRange = "+"+( doc.pages[p].documentOffset+1 ) + "," + "+"+( doc.pages[p+1].documentOffset+1 );
         
         doc.exportFile(ExportFormat.PDF_TYPE, File(mySelectedFolder +"/"+ pdf_name + ".pdf"), false, export_preset);
}
alert("Done Exporting Pdf's!");
}

//Selected Pages/////////////////////////////////////////////////////////////////////////////////////////////

 if (SelectedPages == true){
     
  for(var p = 0; p < app.documents[0].pages.length; p=p+2) {  
    var frames = app.documents[0].pages[p].textFrames;  
    var pdf_name = null;  
    
     for(i = 0; i < frames.length; i++) {
     try {
       if(frames[i].paragraphs[0].appliedParagraphStyle.name == 'PDF_name') {  
          pdf_name = frames[i].paragraphs[0].contents;  
          break;
          }  
       }catch (e){
     }
   }
     
     if (pdf_name == null) { 
    alert ('Error!\nThe Paragraph Style "PDF_name" is not applied to one or more of the pages or is Labeled Incorrectly.');
    exit();
      }
      if(!pdf_name) continue;
      }
  
    var selectPgs = new Window ("dialog", "Select Page#'s To Export");
    var pgGroup = selectPgs.add("group");
    pgGroup.orientation = "column";
    pgGroup.alignChildren = "center";
    pgGroup.add("statictext", undefined, "Export 2-Page pdf's");
    var pgsList = pgGroup.add("listbox", [-25, 0, 170, 246], oddPages, {multiselect: true});
    var selectedpgsList = []; 
    for (var i = 0; i < pgsList.items.length; i++){selectedpgsList[-1] = pgsList.items[i];}
    pgsList.selection = selectedpgsList; 

    var btn = selectPgs.add("group");
    btn.orientation = "row";
    btn.alignment = ["right", "top"];
    var okBtn = btn.add ("button", undefined, "OK", {name:"OK"});
    var cancelBtn = btn.add ("button", undefined, "Cancel", {name:"Cancel"});

    var result = selectPgs.show();
    if(result == 1){
    }  
    else if (result== 2){  
    alert("Canceled!");  
    exit(0);  
    } 
    var pagelist = [];
    if(pgsList.selection == null){
     alert ("Error!\nNo page#'s were selected.")
     exit(); 
     }else{
         
      for (var i=0; i<pgsList.selection.length; i++) {
      pagelist.push(pgsList.selection[i].text);
        }
     }
 
          for (i = 0; i < doc.pages.length; i++) {
            if (String(pagelist).match("\\b"+doc.pages[i].name+"\\b")){ 

            var pdf_name = getTextFromPageUsingParagraphStyle(doc.pages[i]);
          
            app.pdfExportPreferences.pageRange = "+"+( doc.pages[i].documentOffset+1) + "," + "+"+( doc.pages[i+1].documentOffset+1);
           
           doc.exportFile(ExportFormat.PDF_TYPE, File(mySelectedFolder +"/"+ pdf_name + ".pdf"), false, export_preset);
         }
      }
 
app.scriptPreferences.enableRedraw = false;  
w = new Window('window', 'Exporting Pdfs');  
pb = w.add('progressbar', [12, 24, 375, 36], 0, 100);  
w.show();  
for (i = 0; i < 100; i++){  
  pb.value = i;  
  w.update();  
  $.sleep(10);  
}  
w.close();

alert("Done Exporting Pdf's!");
}

 

Regards,

Mike

3 replies

rob day
Community Expert
Community Expert
May 27, 2022

Another way to do it might be to give the name text field in your data merge document a script label before you create the merged document. Something like this:

 

 

 

 

 

Then add a function to check the page’s text frames for the label and get the contents:

 

 

 

 

 


//Exports PDFs in odd-even page ranges
var scriptLabel = "Name"
var f = Folder.selectDialog("Select the folder", ""); 
var doc = app.activeDocument;
var pgs = doc.pages;
var pth, pr;

var preset=app.pdfExportPresets.itemByName("[PDF/X-4:2008]");

for (var i = 0; i < pgs.length; i++){
    if (getEven(i)) {
        pr = pgs[i].name + "-" + pgs[i+1].name;
        app.pdfExportPreferences.properties={pageRange:pr, viewPDF:false}
        pth = f + "/" + (i+1) + "_" + getName(pgs[i], scriptLabel) + ".pdf";
        doc.exportFile(ExportFormat.pdfType, File(pth), false, preset);
    }
};   


/**
* Check n is even 
* @ param the number to check 
* @ return true for even false for odd
*/
function getEven(n){
    if (n%2 == 0) {
        return true
    } else {
        return false
    }   
}

/**
* Gets the contents of a text frame with a script label 
* @ param the page to check 
* @ param the text frame’s script label 
* @ return text frame‘s contents 
* 
*/
function getName(pg, n){
    var tf = pg.textFrames;
    var fn = "No Name";

    for (var i = 0; i < tf.length; i++){
        if (tf[i].label == n) {
            fn = tf[i].contents
        } 
    };   

    return fn
}

 

 

 

 

 

 

 

jelux
jeluxAuthor
Participating Frequently
May 27, 2022

Many thanks I will definitely prove that this system, the other works only that I have to include the field inside the layout because if I put it out it does not match it to the csv so I entered a field with white text

 

Thank you very much

Legend
May 27, 2022

Hello @jelux,

 

Re: "The other works only that I have to include the field inside the layout because if I put it out it does not match it to the csv so I entered a field with white text"

 

Create a text box in the slug area with a portion of the box within the page bounds and assign the Paragraph style "PDF_name" (see screenshot) this way you don't have to have it in the layout with white text.

 

 

Regards,

Mike

rob day
Community Expert
Community Expert
May 27, 2022

Hi @jelux , It’s not too difficult to export pages in pairs. This exports odd-even pairs with the page range included in the file names:

 

 

var f = Folder.selectDialog("Select the folder", ""); 
var doc = app.activeDocument;
var pgs = doc.pages;
var pth, pr;

var preset=app.pdfExportPresets.itemByName("[PDF/X-4:2008]");

for (var i = 0; i < pgs.length; i++){
    if (getEven(i)) {
        pr = pgs[i].name + "-" + pgs[i+1].name;
        app.pdfExportPreferences.properties = {pageRange:pr, viewPDF:false}
        pth = f + "/" +  doc.name + "_Pages" + pr + ".pdf";
        doc.exportFile(ExportFormat.pdfType, File(pth), false, preset);
    }
};   


/**
* Check n is even 
* @ param the number to check 
* @ return true for even false for odd
*/
function getEven(n){
    if (n%2 == 0) {
        return true
    } else {
        return false
    }   
}

 

 

 

 

If you want the PDF file names to include the card name, you would have to find a way to get the contents of the datamerge name field. You could add a script label to the name text frame before you run the datamerge and the the script could loop through the page’s text frames and find the name for the PDF file name

jelux
jeluxAuthor
Participating Frequently
May 27, 2022

Many thanks for this script which works perfectly

 

I'm not very familiar with scripts so I don't know how to connect the names as well it would be nice to be able to export the pdf files with their names

 

any suggestions ?  thank you very much

 

Mike BroCorrect answer
Legend
May 27, 2022

Hello @jelux.

Sorry for the delayed response...

Re: "I'm not very familiar with scripts so I don't know how to connect the names as well it would be nice to be able to export the pdf files with their names

any suggestions ?"

 

Give this a try...

1. Start off by creating a Paragraph style named "PDF_name"

2. Create a text box and assign the Paragraph style "PDF_name"

3. Assign the field from the data source for the pdf naming

4. Create and save the Merged document, run the script to export the pdfs


The below script will export pdfs named by the contents of the text box useing the Paragraph style named "PDF_name".

   var doc = app.documents[0];
   var export_preset = app.pdfExportPresets.item("[High Quality Print]");

   var myResult = {};
   var allStoriesArray = app.documents[0].stories.everyItem().getElements();
   
    for(var n=0; n<allStoriesArray.length; n++){
    var currentStory =  allStoriesArray[n];
    var textContainersLength = currentStory.textContainers.length;
    var lastFrameOfStory = currentStory.textContainers[textContainersLength-1];
    var objToCheck = lastFrameOfStory;
    
    if(lastFrameOfStory.constructor.name == "TextPath")
    objToCheck = lastFrameOfStory.parent
    
    if(currentStory.overflows && objToCheck.itemLayer.visible && objToCheck.parentPage != null)
    myResult[objToCheck.parentPage.name] = objToCheck.parentPage.name;
    }
    
    var pageList = new Array;
    for(var a in myResult)
    pageList.push(a);
        
    pageList.sort(function(a,b) {return a-b});
    
    if(pageList.length > 0){
    alert("Error!\nDocument contains overset text on page(s): \r" + pageList);
    exit();
    }
    
var myPages = [];
for (var i=0; i<doc.pages.length; i ++) {
 myPages.push(app.activeDocument.pages[i].name);
}

// Function Returns "oddPages"
var myPageNums = (myPages);
var oddPages = [];

var oddNumbers = function(myPageNums) {
for (var i = 0; i < myPageNums.length; i++) {

   if ((myPageNums[i] % 2) ==1) {
    oddPages.push(myPageNums[i]);      
   }
  }
}
oddNumbers(myPageNums);


       //Function Returns pdf_name for Selected Pages
      function getTextFromPageUsingParagraphStyle(myPage){
     
     if (doc.paragraphStyles.itemByName("PDF_name") == null) {
      alert ('Error!\nThe Paragraph Style "PDF_name" does not exist or is Labeled Incorrectly.');
      exit();
}
          app.findTextPreferences = app.changeTextPreferences = null;   
          app.findTextPreferences.appliedParagraphStyle = "PDF_name";  
  
          var myTextframes = myPage.textFrames;  
          var pdf_name = null;
          
          for (y=0; y < myTextframes.length; y++){  
                var mySearchResult = myTextframes[y].findText();  
                if (mySearchResult.length > 0){  
                pdf_name = mySearchResult[0].contents; 
                 break;  
                }  
          } 
      
         return pdf_name;      
} 

//Dialog/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var mySelectedFolder = Folder.selectDialog ("Select a Folder");
if(mySelectedFolder  != null){

}else{
    alert ("Canceled!");
    exit();
}

var myDialog = app.dialogs.add({name:"DataMerge 2-Page HR Pdf Exporter", canCancel:true});
with (myDialog){
with (dialogColumns.add()){

with (dialogRows.add())
staticTexts.add({staticLabel:"Page Range Options", minWidth:25});
with (borderPanels.add()){
var myradiogroup1 = radiobuttonGroups.add();
with (myradiogroup1){
var myyesradiobutton1 = radiobuttonControls.add({staticLabel:'Export All Pages', checkedState:true});
var mynoradiobutton1 = radiobuttonControls.add({staticLabel:'Export Select Pages'});    
staticTexts.add({staticLabel:"", minWidth:75});  
}
}
}
}
if (myDialog.show() == true){

var SelectedPages = myradiogroup1.selectedButton; 

}else{
}
myDialog.destroy();

//All Pages//////////////////////////////////////////////////////////////////////////////////////////////////

 if (SelectedPages == false){
     
  for(var p = 0; p < app.documents[0].pages.length; p=p+2) {  
    var frames = app.documents[0].pages[p].textFrames;  
    var pdf_name = null;  
 
    for(i = 0; i < frames.length; i++) {
     try {
       if(frames[i].paragraphs[0].appliedParagraphStyle.name == 'PDF_name') {  
          pdf_name = frames[i].paragraphs[0].contents;  
          break;
          }  
       }catch (e){
     }
  }

     
    if (pdf_name == null) { 
    alert ('Error!\nThe Paragraph Style "PDF_name" is not applied to one or more of the pages or is Labeled Incorrectly.');
    exit();
    }
      
      if(pdf_name != null) {  
 
    }    

app.scriptPreferences.enableRedraw = false;  
w = new Window('window', 'Exporting Pdfs');  
pb = w.add('progressbar', [12, 24, 375, 36], 0, 100);  
w.show();  
for (i = 0; i < 100; i++){  
  pb.value = i;  
  w.update();  
  $.sleep(10);  
}  
w.close();

app.pdfExportPreferences.pageRange = "+"+( doc.pages[p].documentOffset+1 ) + "," + "+"+( doc.pages[p+1].documentOffset+1 );
         
         doc.exportFile(ExportFormat.PDF_TYPE, File(mySelectedFolder +"/"+ pdf_name + ".pdf"), false, export_preset);
}
alert("Done Exporting Pdf's!");
}

//Selected Pages/////////////////////////////////////////////////////////////////////////////////////////////

 if (SelectedPages == true){
     
  for(var p = 0; p < app.documents[0].pages.length; p=p+2) {  
    var frames = app.documents[0].pages[p].textFrames;  
    var pdf_name = null;  
    
     for(i = 0; i < frames.length; i++) {
     try {
       if(frames[i].paragraphs[0].appliedParagraphStyle.name == 'PDF_name') {  
          pdf_name = frames[i].paragraphs[0].contents;  
          break;
          }  
       }catch (e){
     }
   }
     
     if (pdf_name == null) { 
    alert ('Error!\nThe Paragraph Style "PDF_name" is not applied to one or more of the pages or is Labeled Incorrectly.');
    exit();
      }
      if(!pdf_name) continue;
      }
  
    var selectPgs = new Window ("dialog", "Select Page#'s To Export");
    var pgGroup = selectPgs.add("group");
    pgGroup.orientation = "column";
    pgGroup.alignChildren = "center";
    pgGroup.add("statictext", undefined, "Export 2-Page pdf's");
    var pgsList = pgGroup.add("listbox", [-25, 0, 170, 246], oddPages, {multiselect: true});
    var selectedpgsList = []; 
    for (var i = 0; i < pgsList.items.length; i++){selectedpgsList[-1] = pgsList.items[i];}
    pgsList.selection = selectedpgsList; 

    var btn = selectPgs.add("group");
    btn.orientation = "row";
    btn.alignment = ["right", "top"];
    var okBtn = btn.add ("button", undefined, "OK", {name:"OK"});
    var cancelBtn = btn.add ("button", undefined, "Cancel", {name:"Cancel"});

    var result = selectPgs.show();
    if(result == 1){
    }  
    else if (result== 2){  
    alert("Canceled!");  
    exit(0);  
    } 
    var pagelist = [];
    if(pgsList.selection == null){
     alert ("Error!\nNo page#'s were selected.")
     exit(); 
     }else{
         
      for (var i=0; i<pgsList.selection.length; i++) {
      pagelist.push(pgsList.selection[i].text);
        }
     }
 
          for (i = 0; i < doc.pages.length; i++) {
            if (String(pagelist).match("\\b"+doc.pages[i].name+"\\b")){ 

            var pdf_name = getTextFromPageUsingParagraphStyle(doc.pages[i]);
          
            app.pdfExportPreferences.pageRange = "+"+( doc.pages[i].documentOffset+1) + "," + "+"+( doc.pages[i+1].documentOffset+1);
           
           doc.exportFile(ExportFormat.PDF_TYPE, File(mySelectedFolder +"/"+ pdf_name + ".pdf"), false, export_preset);
         }
      }
 
app.scriptPreferences.enableRedraw = false;  
w = new Window('window', 'Exporting Pdfs');  
pb = w.add('progressbar', [12, 24, 375, 36], 0, 100);  
w.show();  
for (i = 0; i < 100; i++){  
  pb.value = i;  
  w.update();  
  $.sleep(10);  
}  
w.close();

alert("Done Exporting Pdf's!");
}

 

Regards,

Mike

Legend
May 27, 2022

Hello @jelux,

I'm sorry even after your explanation it's still not very clear to me how your merged document is setup.

Are you saying that you have a 100 page document with 50 business cards front and back in sequential order?? So the exported pdfs would be... pages 1-2, 3-4, 5-6, 7-8, etc....all named individually by the names that appears on the business cards?

 

Regards,

Mike

jelux
jeluxAuthor
Participating Frequently
May 27, 2022

the file consists of 100 pages 50 are the front of the ticket with 50 different names and surnames inserted with data merge, while the remaining 50 pages are the back of the ticket and are practically all the same, the sequence of the pages and 1-2, 3-4, 5-6, and so on

export pages 1-2 business card double-sided with name 1
export pages 3-4 business card double-sided with name 2
export of pages 5-6 double-sided business card with name 3

Peter Spier
Community Expert
Community Expert
May 27, 2022

Probably easier to script extracting the pairs of pages in Acrobat. You might want to ask over there.