forked from mike-edel/ID-MultiPageImporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiPageImporter.jsx
1782 lines (1573 loc) · 51.6 KB
/
MultiPageImporter.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MultiPageImporter2.6.2 jsx
// An InDesign CS4 JavaScript
// 28 MAR 2010
// Copyright (C) 2008-2009 Scott Zanelli. [email protected]
// Coming to you from South Easton, MA, USA
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// Version 2.1: Fix for CS4 compatibility. (04 MAR 2009)
// Version 2.2: Map pages to exisitng doc pages and reverse the page order options added. (05 MAR 2009)
// Version 2.2.1: Page rotation. (12 MAR 2009)
// Version 2.5: If PDF page count/size can't be determined, import all pages. Remove dependency on Verdana. (28 MAR 2010)
// Version 2.5JJB: Added support for ID CS5 PDF importing. The PDFCrop constants used in IDCS5 are now supported (14 FEB 2011). See lines 126-139. //JJB
// Version 2.6: Fixed a bug that would display a misleading error message ("This value would cause one or more objects to leave the pasteboard.") - mostly in cases where the default font size for a new text box would cause a 20x20 document units box to overflow
// Version 2.6.1: Added new document scale for easy page scaling and tag all placed frames
// Version 2.6.2: Added very basic support for .ai files that are written as pdf compatible files - basically using the pdf code for them - allows for automatically placing multi-artboard AIs
// Get app version and save old interation setting.
// Some installs have the interaction level set to not show any dialogs.
// This is used to insure that the dialog is shown.
//#target indesign;
var appVersion = parseInt(app.version);
// Only works in CS3+
if(appVersion >= 5)
{
var oldInteractionPref = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
}
else
{
alert("Features used in this script will only work in InDesign CS3 or later.");
exit(-1);
}
// Set the next line to false to not use prefs
var usePrefs = true;
// Set default prefs
var pdfCropType = 0;
var indCropType = 1;
var offsetX = 0;
var offsetY = 0;
var doTransparent = 1;
var placeOnLayer = 0;
var fitPage = 0;
var keepProp = 0;
var addBleed = 1;
var ignoreErrors = 0;
var percX = 100;
var percY = 100;
var mapPages = 0;
var reverseOrder = 0;
var rotate = 0;
var positionType = 4; // 4 = center
// Do not change anything after this line!
// removed 6/25/08: var indUpdateType = 0;
var cropType = 0;
var PDF_DOC = "PDF";
var IND_DOC = "InDesign";
var tempObjStyle = null;
var dLog; // Kludge for callback function that uses the dLog, but can't be given the dLog directly
var ddArray;
var ddIndexArray;
var numArray;
var getout;
var doMapCheck = true;
var rotateValues = [0,90,180,270];
var positionValuesAll = ["Top left", "Top center", "Top right", "Center left", "Center", "Center right", "Bottom left", "Bottom center", "Bottom right"];
var noPDFError = true;
// Look for and read prefs file
prefsFile = File((Folder(app.activeScript)).parent + "/MultiPageImporterPrefs2.5.txt");
if(!prefsFile.exists)
{
savePrefs(true);
}
else
{
readPrefs();
}
// Ask user to select the PDF/InDesign file to place
var askIt = "Select a PDF, PDF compatible AI or InDesign file to place:";
if (File.fs =="Windows")
{
var theFile = File.openDialog(askIt, "Placeable: *.indd;*.pdf;*.ai");
}
else if (File.fs == "Macintosh")
{
var theFile = File.openDialog(askIt, macFileFilter);
}
else
{
var theFile = File.openDialog(askIt);
}
// Check if cancel was clicked
if (theFile == null)
{
// user clicked cancel, just leave
exit();
}
// Check if a file other than PDF or InDesign chosen
else if((theFile.name.toLowerCase().indexOf(".pdf") == -1 && theFile.name.toLowerCase().indexOf(".ind") == -1 && theFile.name.toLowerCase().indexOf(".ai") == -1 ))
{
restoreDefaults(false);
throwError("A PDF, PDF compatible AI or InDesign file must be chosen. Quitting...", false, 1, null);
}
var fileName = File.decode(theFile.name);
// removed 6/25/08: var indUpdateStrings = ["Use Doc's Layer Visibility","Keep Layer Visibility Overrides"];
if((theFile.name.toLowerCase().indexOf(".pdf") != -1) || (theFile.name.toLowerCase().indexOf(".ai") != -1))
{
// Premedia Systems/JJB Edit Start - 02/14/11 Modified PDFCrop constants to support ID CS3 through CS5 PDFCrop Types.
if (appVersion > 6)
{
// CS5 or newer
var cropTypes = [PDFCrop.cropPDF, PDFCrop.cropArt, PDFCrop.cropTrim, PDFCrop.cropBleed, PDFCrop.cropMedia, PDFCrop.cropContentAllLayers, PDFCrop.cropContentVisibleLayers];
var cropStrings = ["Crop","Art","Trim","Bleed", "Media","All Layers Bounding Box","Visible Layers Bounding Box"];
}
else
{
// CS3 or CS4
var cropTypes = [PDFCrop.cropContent, PDFCrop.cropArt, PDFCrop.cropPDF, PDFCrop.cropTrim, PDFCrop.cropBleed, PDFCrop.cropMedia];
var cropStrings = ["Bounding Box","Art","Crop","Trim","Bleed", "Media"];
}
// Premedia Systems/JJB Edit End
// Parse the PDF file and extract needed info
try
{
var placementINFO = getPDFInfo(theFile, (app.documents.length == 0));
}
catch(e)
{
// Couldn't determine the PDF info, revert to just adding all the pages
noPDFError = false;
placementINFO = new Array();
if(app.documents.length == 0)
{
var tmp = new Array();
tmp["width"] = 612;
tmp["height"] = 792;
placementINFO["pgSize"] = tmp;
}
}
placementINFO["kind"] = PDF_DOC;
}
else
{
var cropTypes = [ImportedPageCropOptions.CROP_CONTENT, ImportedPageCropOptions.CROP_BLEED, ImportedPageCropOptions.CROP_SLUG];
var cropStrings = ["Page bounding box","Bleed bounding box","Slug bounding box"];
// Get the InDesign doc's info
var placementINFO = getINDinfo(theFile);
placementINFO["kind"] = IND_DOC;
}
// If there is no document open, create a new one using the size of the
// first encountered page
var theDocIsMine = false; // Is the doc created by this script boolean
if(app.documents.length == 0)
{
// Save the app measurement units to restore after doc is created
var oldUnitsV = app.viewPreferences.verticalMeasurementUnits;
var oldUnitsH = app.viewPreferences.horizontalMeasurementUnits;
var oldMarginT = app.marginPreferences.top;
var oldMarginB = app.marginPreferences.bottom;
var oldMarginL = app.marginPreferences.left;
var oldMarginR = app.marginPreferences.right;
app.marginPreferences.top = 0;
app.marginPreferences.bottom = 0;
app.marginPreferences.left = 0;
app.marginPreferences.right = 0;
if(placementINFO.kind == PDF_DOC)
{
app.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
app.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
}
else
{
app.viewPreferences.verticalMeasurementUnits = placementINFO.vUnits;
app.viewPreferences.horizontalMeasurementUnits = placementINFO.hUnits;
}
// Make the new doc:
var theDoc = app.documents.add();
theDocIsMine = true;
theDoc.documentPreferences.facingPages = false;
theDoc.marginPreferences.columnCount = 1;
theDoc.documentPreferences.pageWidth = placementINFO.pgSize.width;
theDoc.documentPreferences.pageHeight = placementINFO.pgSize.height;
theDoc.viewPreferences.verticalMeasurementUnits = oldUnitsV;
theDoc.viewPreferences.horizontalMeasurementUnits = oldUnitsH;
// Restore the original units
app.viewPreferences.verticalMeasurementUnits = oldUnitsV;
app.viewPreferences.horizontalMeasurementUnits = oldUnitsH;
app.marginPreferences.top = oldMarginT;
app.marginPreferences.bottom = oldMarginB;
app.marginPreferences.left = oldMarginL;
app.marginPreferences.right = oldMarginR;
}
else
{
var theDoc = app.activeDocument;
}
var currentLayer = theDoc.activeLayer;
var docPgCount = theDoc.pages.length;
// Get and display the dialog
dLog = makeDialog();
dLog.center(); // Center dialog in screen
if(dLog.show() == 1)
{
// Extract info from dialog info
if(noPDFError)
{
startPG = Number(dLog.startPG.text);
endPG = Number(dLog.endPG.text);
mapPages = Number(dLog.mapPages.value);
reverseOrder = Number(dLog.reverseOrder.value);
}
else
{
startPG = 1;
endPG = 99999;
}
docStartPG = Number(dLog.docStartPG.text);
cropType = dLog.cropType.selection.index;
offsetX = Number(dLog.offsetX.text);
offsetY = Number(dLog.offsetY.text);
percX = Number(dLog.percX.text);
percY = Number(dLog.percY.text);
rotate = dLog.rotate.selection.index;
if(placementINFO.kind == PDF_DOC)
{
doTransparent = dLog.doTransparent.value;
}
ignoreErrors = dLog.ignoreErrors.value;
placeOnLayer = dLog.placeOnLayer.value;
// indUpdateType = dLog.indUpdateType.selection; // Removed 6/25/08
fitPage = dLog.fitPage.value;
keepProp = dLog.keepProp.value;
addBleed = dLog.addBleed.value;
positionType = dLog.posDropDown.selection.index;
}
else
{
restoreDefaults(false);
exit();
}
// Check whether to do page mapping
if(mapPages && noPDFError)
{
ddArray = new Array(docPgCount);
ddIndexArray = new Array(docPgCount);
numArray = new Array(docPgCount+1);
// Fill the ddIndexArray with 1 to # of PDF pages
for(i=startPG, j= 1; i < docPgCount + startPG; i++, j++)
ddIndexArray[i%docPgCount] = j;
// Fill the numArray with all the document page numbers
numArray[0] = "skip";
for(i=1; i<=docPgCount; i++)
numArray[i]=(i).toString();
mapDlog = createMappingDialog(startPG, endPG, numArray);
mapDlog.center();
if(mapDlog.show() == 2)
{
// Cancel clicked
restoreDefaults(false);
exit(0);
}
}
// Dialog is no longer needed, let it eventually be garbage collected
dLog = null;
// Add the new layer if requested
if(placeOnLayer)
{
// Add random number to file name to be layer name.
// Double check layer name doesn't exist and alter if it happens to be present for some reason
var layerName = fileName + "_" + Math.round(Math.random() * 9999);
var docLayers = theDoc.layers;
for(i=0; i < docLayers.length; i++)
{
if (docLayers[i].name.indexOf(layerName) != -1 )
{
layerName += ("_" + Math.round(Math.random() * 9999));
}
}
// Add the layer
currentLayer = theDoc.layers.add({name:layerName});
}
// Save zero point for later restoration
var oldZero = theDoc.zeroPoint;
// set the zero point to the origin
theDoc.zeroPoint = [0,0];
// Save ruler origin for later restoration
var oldRulerOrigin = theDoc.viewPreferences.rulerOrigin;
// set the ruler origin to page or all PDFs will be placed on first page of spreads
theDoc.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
if( theDocIsMine ) {
theDoc.documentPreferences.pageWidth *= percX/100;
theDoc.documentPreferences.pageHeight *= percY/100;
}
// Get the Indy doc's height and width
var docWidth = theDoc.documentPreferences.pageWidth;
var docHeight = theDoc.documentPreferences.pageHeight;
// Set placement prefs
if(placementINFO.kind == PDF_DOC)
{
with(app.pdfPlacePreferences)
{
transparentBackground = doTransparent;
pdfCrop = cropTypes[cropType];
}
}
else
{
app.importedPageAttributes.importedPageCrop = cropTypes[cropType];
}
// Block errors if requested
if(ignoreErrors)
{
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
}
// Create the Object Style to be applied to the placed pages.
var tempObjStyle = theDoc.objectStyles.add();
tempObjStyle.name = "MultiPageImporter_Styler_" + Math.round(Math.random() * 9999);
tempObjStyle.strokeWeight = 0; // Make sure there's no stroke
tempObjStyle.fillColor = "None"; // Make sure fill is none
tempObjStyle.enableAnchoredObjectOptions = true;
// Set the anchor properties
var tempAOS = tempObjStyle.anchoredObjectSettings;
tempAOS.anchoredPosition = AnchorPosition.ANCHORED;
tempAOS.spineRelative = false;
tempAOS.lockPosition = false;
tempAOS.verticalReferencePoint = AnchoredRelativeTo.PAGE_EDGE;
tempAOS.horizontalReferencePoint = AnchoredRelativeTo.PAGE_EDGE;
tempAOS.anchorXoffset = offsetX;
tempAOS.anchorYoffset = offsetY;
// Set the placement options based on user selected position
// The -1 is needed to get rectangle to move correctly when using the auto positioning of the object styles
// Could be a bug since just the left positions need the negative multiple (spine doesn't need the negative multiple)
switch(positionType)
{
case 0: // Top Left
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.TOP_LEFT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.TOP_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.LEFT_ALIGN;
break;
case 1: // Top Center
tempAOS.anchorPoint = AnchorPoint.TOP_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.TOP_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.CENTER_ALIGN;
break;
case 2: // Top Right
tempAOS.anchorPoint = AnchorPoint.TOP_RIGHT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.TOP_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
case 3: // Middle Left
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.LEFT_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.CENTER_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.LEFT_ALIGN;
break;
case 4: // Center
tempAOS.anchorPoint = AnchorPoint.CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.CENTER_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.CENTER_ALIGN;
break;
case 5: // Middle Right
tempAOS.anchorPoint = AnchorPoint.RIGHT_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.CENTER_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
case 6: // Bottom Left
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.BOTTOM_LEFT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.BOTTOM_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.LEFT_ALIGN;
break;
case 7: // Bottom Center
tempAOS.anchorPoint = AnchorPoint.BOTTOM_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.BOTTOM_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.CENTER_ALIGN;
break;
case 8: // Bottom Right
tempAOS.anchorPoint = AnchorPoint.BOTTOM_RIGHT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.BOTTOM_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
// 9 == separator
case 10: // Top Relative to Spine
tempAOS.spineRelative = true;
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.TOP_RIGHT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.TOP_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
case 11: // Middle Relative to Spine
tempAOS.spineRelative = true;
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.RIGHT_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.CENTER_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
case 12: // Bottom Relative to Spine
tempAOS.spineRelative = true;
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.BOTTOM_RIGHT_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.BOTTOM_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.RIGHT_ALIGN;
break;
case 13: // Middle relative to Edge
tempAOS.spineRelative = true;
tempAOS.anchorXoffset *= -1;
tempAOS.anchorPoint = AnchorPoint.LEFT_CENTER_ANCHOR;
tempAOS.verticalAlignment = VerticalAlignment.CENTER_ALIGN;
tempAOS.horizontalAlignment = HorizontalAlignment.LEFT_ALIGN;
break;
}
// Add the pages to the doc based on normal or mapping pages
if(mapPages && noPDFError)
{
for(pdfPG = startPG; pdfPG <= endPG; pdfPG++)
{
i = ddArray[pdfPG%docPgCount].selection.text;
if(i == "skip")
{
continue;
}
addPages(Number(i), pdfPG, pdfPG);
}
}
else if(reverseOrder && noPDFError)
{
for(reverse = endPG; reverse >= startPG; reverse--)
{
addPages(docStartPG, reverse, reverse);
docStartPG++;
}
}
else
{
addPages(docStartPG, startPG, endPG);
}
// Kill the Object style
tempObjStyle.remove();
// Save prefs and then restore original app/doc settings
savePrefs(false);
restoreDefaults(true);
// THE END OF EXECUTION
exit();
// Place the requested pages in the document
function addPages(docStartPG, startPG, endPG)
{
var currentPDFPg = 0;
var firstTime = true;
var addedAPage = false;
var zeroBasedDocPgCnt = docPgCount - 1;
for(i = docStartPG - 1, currentInputDocPg = startPG; currentInputDocPg <= endPG; currentInputDocPg++, i++)
{
if(placementINFO.kind == PDF_DOC)
{
// Set the app's PDF placement pref's page number property to the current PDF page number
app.pdfPlacePreferences.pageNumber = currentInputDocPg;
}
else
{
// Set the app's Imported Page placement pref's page number property to the current IND page number
app.importedPageAttributes.pageNumber = currentInputDocPg;
}
if(i > zeroBasedDocPgCnt)
{
// Make sure we have a page to insert into
theDoc.pages.add(LocationOptions.AT_END);
addedAPage = true;
}
// Create a temporary text box to place graphic in (to use auto positioning and sizing)
var TB = theDoc.pages[i].textFrames.add({geometricBounds:[0,0,20,20]});
//decrease the font size of the newly inserted box to 0 to avoid a very misleading "out of pasteboard" error
//background: if the default font size of the ID document (set by default character style or default paragraph style) causes the text box to overflow it gives you an error saying ("This value would cause one or more objects to leave the pasteboard."). This mainly manifests in pixel based documents as the text box is only 20x20 px large in those cases.
TB.texts.firstItem().pointSize=1;
var theRect = TB.insertionPoints.firstItem().rectangles.add();
theRect.label = "Multi_Page_Importer_Rect";
// Applying the object style and doing a recompose updates some objects that
// the add method doesn't create in the rectangle object
theRect.appliedObjectStyle = tempObjStyle;
TB.recompose();
// Place the current PDF/Ind page into the rectangle object
try
{
var tempGraphic = theRect.place(theFile)[0];
/* removed 6/25/08
tempGraphic.graphicLayerOptions.updateLinkOption = (indUpdateType == 0) ?
UpdateLinkOptions.APPLICATION_SETTINGS :
UpdateLinkOptions.KEEP_OVERRIDES;
*/
// If all pgs are being added, check that we aren't cruising to the first PDF page again
if(!noPDFError && !firstTime && tempGraphic.pdfAttributes.pageNumber == 1)
{
// If a page was added, nuke it, it's a dupe of the first page
if(addedAPage)
{
theDoc.pages[i].remove();
}
else
{
// Just remove the placed graphic
TB.remove();
}
return;
}
}
catch(e)
{
if(e.description.indexOf("Failed to open") != -1 )
{
alert("\"" + fileName + "\" doesn't contain a \"" + cropStrings[cropType] + "\" crop type:\n\nPlease try again by selecting a different crop type or open\nthe PDF in Acrobat and perform a \"Save As...\" command.", "PDF Placement Error");
}
else
{
alert(e);
}
if(placeOnLayer)
{
currentLayer.remove();
}
else
{
TB.remove();
}
restoreDefaults(true);
// Kill the Object style
tempObjStyle.remove();
exit(-1);
}
// Apply any rotation
theRect.rotationAngle = rotateValues[rotate];
// Fit to Page Option
if(fitPage)
{
if(addBleed)
{
// Make rectangle the size of the page size plus bleed
theRect.geometricBounds = [
0 - theDoc.documentPreferences.documentBleedTopOffset,
0 - theDoc.documentPreferences.documentBleedInsideOrLeftOffset,
docHeight + theDoc.documentPreferences.documentBleedBottomOffset,
docWidth + theDoc.documentPreferences.documentBleedOutsideOrRightOffset];
}
else
{
// Change rectangle's size to the page size
theRect.geometricBounds = [0, 0, docHeight, docWidth];
}
// Fit the placed page according to selected options
if(keepProp)
{
theRect.fit(FitOptions.FILL_PROPORTIONALLY);
theRect.fit(FitOptions.frameToContent);// Size box down to size of placed page
}
else
theRect.fit(FitOptions.contentToFrame);
}
// Use the Scaling Option
else
{
// Apply the scaling
theRect.allGraphics[0].verticalScale = percY;
theRect.allGraphics[0].horizontalScale = percX;
theRect.fit(FitOptions.frameToContent);
}
// Apply the Object Style to transform the graphic into an anchored item (allows auto positioning)
theRect.appliedObjectStyle = tempObjStyle;
// Force the text box to reformat itself in order to apply the Object Style
TB.recompose();
// Release the placed page from the text box and then delete the text box (clean up)
theRect.anchoredObjectSettings.releaseAnchoredObject();
TB.remove();
firstTime = false;
}
}
// Create the main dialog box
function makeDialog()
{
dLog = new Window('dialog', "Import Multiple " + placementINFO.kind + " Pages",
"x:100, y:100, width:533, height:365"); // old height before update option removed: 395
dLog.onClose = ondLogClosed;
/******************/
/* Upper Left Panel */
/******************/
dLog.pan1 = dLog.add('panel', [15,15,200,193], "Page Selection");
dLog.pan1.add('statictext', [10,15,170,35], "Import " + placementINFO.kind + " Pages:");
if(noPDFError)
{
// Start pg
dLog.startPG = dLog.pan1.add('edittext', [10,40,70,63], "1");
dLog.startPG.onChange = startPGValidator;
dLog.pan1.add('statictext', [75,45,102,60], "thru");
// End page
dLog.endPG = dLog.pan1.add('edittext', [105,40,165,63], placementINFO.pgCount);
dLog.endPG.onChange = endPGValidator;
// Mapping option
dLog.mapPages = dLog.pan1.add('checkbox', [10,144,175,164], "Map to Doc Pages");
if(reverseOrder || docPgCount == 1)
{
mapPages = false;
dLog.mapPages.enabled = false;
}
dLog.mapPages.value = mapPages;
dLog.mapPages.onClick = mapPGValidator;
// Reverse order
dLog.reverseOrder = dLog.pan1.add('checkbox', [10,70,190,85], "Reverse Page Order");
if(mapPages)
{
// Both Mapping and reverse can't be checked
reverseOrder = false;
dLog.reverseOrder.enabled = false;
}
dLog.reverseOrder.value = reverseOrder;
dLog.reverseOrder.onClick = reverseClicked;
}
else
{
dLog.pan1.add('statictext', [10,40,190,55], "Cannot determine PDF");
dLog.pan1.add('statictext', [10,55,190,70], "page count: all pages");
dLog.pan1.add('statictext', [10,70,190,85], "will be imported.");
}
// Doc start page
dLog.pan1.add('statictext', [10,94,190,109], "Start Placing on Doc Page:");
dLog.docStartPG = dLog.pan1.add('edittext', [10,114,70,137], "1");
dLog.docStartPG.onChange = docStartPGValidator;
/***********************/
/* Lower Left Panel */
/***********************/
dLog.pan2 = dLog.add('panel', [15,200,200,350], "Sizing Options");
// BEGIN Fitting Section
dLog.fitPage = dLog.pan2.add('checkbox', [10,15,100,35], "Fit to Page");
dLog.fitPage.onClick = onFitPageClicked;
dLog.fitPage.value = fitPage;
// Checkbox
dLog.keepProp = dLog.pan2.add('checkbox', [10,35,160,55], "Keep Proportions");
dLog.keepProp.value = keepProp;
dLog.keepProp.enabled = dLog.fitPage.value;
// Checkbox
dLog.addBleed = dLog.pan2.add('checkbox', [10,55,160,75], "Bleed the Fit Page");
dLog.addBleed.value = addBleed;
dLog.addBleed.enabled = dLog.fitPage.value;
// END Fitting Section
// BEGIN Scaling section
dLog.pan2.add('statictext', [10,80,200,95], "Scale of Imported Page:");
// X%
dLog.pan2.add('statictext', [10,105,35,125], "X%:");
dLog.percX = dLog.pan2.add('edittext', [42,102,82,125], "100");
dLog.percX.text = percX;
// Visibility depends on the Fit Page checkbox
dLog.percX.enabled = !dLog.fitPage.value;
// Assign a validator
dLog.percX.onChange = percXValidator;
// Y%
dLog.pan2.add('statictext', [87,105,112,125], "Y%:");
dLog.percY = dLog.pan2.add('edittext', [119,102,159,125], "100");
dLog.percY.text = percY;
// Visibility depends on the Fit Page checkbox
dLog.percY.enabled = !dLog.fitPage.value;
// Assign a validator
dLog.percY.onChange = percYValidator;
/*************************/
/* Upper Right Panel */
/*************************/
dLog.pan3 = dLog.add('panel', [210,15,438,193], "Positioning Options");
dLog.pan3.add('statictext', [10,15,228,35], "Position on Page Aligned From:");
// DropDownList
dLog.posDropDown = dLog.pan3.add('dropdownlist', [10,40,215,60], positionValuesAll);
dLog.posDropDown.add("separator");
dLog.posDropDown.add("item", "Top, relative to spine");
dLog.posDropDown.add("item", "Center, relative to spine");
dLog.posDropDown.add("item", "Bottom, relative to spine");
dLog.posDropDown.selection = positionType;
// Rotation
dLog.pan3.add('statictext', [10,70,85,90], "Rotatation:");
dLog.rotate = dLog.pan3.add('dropdownlist', [85,67,215,88]);
for(i=0;i<rotateValues.length;i++)
{
dLog.rotate.add('item', rotateValues[i]);
}
dLog.rotate.selection = rotate;
// Offset section
dLog.pan3.add('statictext', [10,97,150,117], "Offset by:");
// X offset value
dLog.pan3.add('statictext', [10,122,25,142], "X:");
dLog.offsetX = dLog.pan3.add('edittext', [30,119,95,142], offsetX);
dLog.offsetX.onChange = offsetXValidator;
// Y offset value
dLog.pan3.add('statictext', [100,122,115,142], "Y:");
dLog.offsetY = dLog.pan3.add('edittext', [120,119,185,142], offsetY);
dLog.offsetY.onChange = offsetYValidator;
/*************************/
/* Lower Right Panel */
/*************************/
/* old position before removing update option: [210,207,427,380] */
dLog.pan4 = dLog.add('panel', [210,200,438,350], "Placement Options");
// Add the crop type dropdown list and populate it
dLog.pan4.add('statictext', [10,18,60,35], "Crop to:");
dLog.cropType = dLog.pan4.add('dropdownlist', [65,15,215,33]);
for(i=0;i<cropStrings.length;i++)
{
dLog.cropType.add('item', cropStrings[i]);
}
dLog.cropType.selection = (placementINFO.kind == PDF_DOC)? pdfCropType : indCropType;
// Place on Layer
dLog.placeOnLayer = dLog.pan4.add('checkbox', [10,44,220,60], "Place Pages on a New Layer");
dLog.placeOnLayer.value = placeOnLayer;
// Ignore errors
dLog.ignoreErrors = dLog.pan4.add('checkbox', [10,65,220,81], "Ignore Font and Image Errors");
dLog.ignoreErrors.value = ignoreErrors;
// Update Link Options
/* As of 6/26/08, removing this option so dialog will look better
dLog.pan4.add('statictext', [10,85,190,100], "Update Link Options:");
dLog.indUpdateType = dLog.pan4.add('dropdownlist', [10,105,200,125]);
for(i = 0; i < indUpdateStrings.length;i++)
{
dLog.indUpdateType.add('item', indUpdateStrings[i]);
}
dLog.indUpdateType.selection = indUpdateType;
*/
// Transparent PDFs
/* old position before removing update option: [10,133,190,152] */
dLog.doTransparent = dLog.pan4.add('checkbox', [10,86,220,100], "Transparent PDF Background");
dLog.doTransparent.value = doTransparent;
// Disable PDF options if needed
if(placementINFO.kind != PDF_DOC)
{
dLog.doTransparent.enabled = false;
}
// The buttons
dLog.OKbut = dLog.add('button', [448,20,507,45], "OK");
dLog.OKbut.onClick = onOKclicked;
dLog.CANbut = dLog.add('button', [448,50,507,75], "Cancel");
dLog.CANbut.onClick = onCANclicked;
return dLog;
}
// function to restore saved settings back to originals before script ran
// extras parameter is for exiting at different areas of script:
// false: prior to doing anything
// true: end of script or reading PDF file size
function restoreDefaults(extras)
{
app.scriptPreferences.userInteractionLevel = oldInteractionPref;
if(extras == true)
{
theDoc.zeroPoint = oldZero;
theDoc.viewPreferences.rulerOrigin = oldRulerOrigin;
}
}
// function to read prefs from a file
function readPrefs()
{
if(usePrefs)
{
try
{
prefsFile.open("r");
pdfCropType = Number(prefsFile.readln() );
positionType = Number(prefsFile.readln() );
offsetX = Number(prefsFile.readln() );
offsetY = Number(prefsFile.readln() );
doTransparent = Number(prefsFile.readln() );
placeOnLayer = Number(prefsFile.readln() );
fitPage = Number(prefsFile.readln() );
keepProp = Number(prefsFile.readln() );
addBleed = Number(prefsFile.readln() );
ignoreErrors = Number(prefsFile.readln() );
percX = Number(prefsFile.readln() );
percY = Number(prefsFile.readln() );
indCropType = Number(prefsFile.readln() );
mapPages = Number(prefsFile.readln() );// added 9/7/08
reverseOrder = Number(prefsFile.readln() ); // added 1/17/09
rotate = Number(prefsFile.readln()); // added 3/6/09
prefsFile.close();
}
catch(e)
{
throwError("Could not read preferences: " + e, false, 2, prefsFile);
}
}
}
// function to save prefs to a file
function savePrefs(firstRun)
{
if(usePrefs)
{
try
{
var newPrefs =
((!firstRun && placementINFO.kind == PDF_DOC) ? cropType: pdfCropType) + "\n" +
positionType + "\n" +
offsetX + "\n" +
offsetY + "\n" +
((doTransparent)?1:0) + "\n" +
((placeOnLayer)?1:0) + "\n" +
((fitPage)?1:0) + "\n" +
((keepProp)?1:0) + "\n" +
((addBleed)?1:0) + "\n" +
((ignoreErrors)?1:0) + "\n" +
percX + "\n" +
percY + "\n" +
((!firstRun && placementINFO.kind == IND_DOC) ? cropType : indCropType) + "\n" +
((mapPages)?1:0) + "\n" + /* added 9/7/08 */
((reverseOrder)?1:0) + "\n" +/* added 1/17/09 */
rotate; /* added 3/6/09 */
prefsFile.open("w");
prefsFile.write(newPrefs);
prefsFile.close();
}
catch(e)
{
throwError("Could not save preferences: " + e, false, 2, prefsFile);
}
}
}
/*********************************************/
/* */
/* PDF READER SECTION */
/* Extracts count and size of pages */
/* */
/********************************************/
// Extract info from the PDF file.
// getSize is a boolean that will also determine page size and rotation of first page
// *** File position changes in this function. ***
// Results are as follows:
// page count = retArray.pgCount
// page width = retArray.pgSize.pgWidth
// page height = retArray.pgSize.pgHeight
function getPDFInfo(theFile, getSize)
{
var flag = 0; // used to keep track if the %EOF line was encountered
var nlCount = 0; // number of newline characters per line (1 or 2)
// The array to hold return values
var retArray = new Array();
retArray["pgCount"] = -1;
retArray["pgSize"] = null;
// Open the PDF file for reading
theFile.open("r");
// Search for %EOF line
// This skips any garbage at the end of the file
// if FOE% is encountered (%EOF read backwards), flag will be 15
for(i=0; flag != 15; i++)
{
theFile.seek(i,2);
switch(theFile.readch())
{
case "F":
flag|=1;
break;
case "O":
flag|=2;
break;
case "E":
flag|=4;
break;
case "%":
flag|=8;
break;
default:
flag=0;
break;
}
}
// Jump back a small distance to allow going forward more easily
theFile.seek(theFile.tell()-100);
// Read until startxref section is reached
while(theFile.readln() != "startxref");
// Set the position of the first xref section
var xrefPos = parseInt(theFile.readln(), 10);
// The array for all the xref sections
var xrefArray = new Array();
// Go to the xref section
theFile.seek(xrefPos);
// Determine length of xref entries
// (not all PDFs are compliant with the requirement of 20 char/entry)
xrefArray["lineLen"] = determineLineLen(theFile);
// Get all the xref sections
while(xrefPos != -1)
{
// Go to next section
theFile.seek(xrefPos);
// Make sure it's an xref line we went to, otherwise PDF is no good
if (theFile.readln() != "xref")
{
throwError("Cannot determine page count.", true, 99, theFile);
}