-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathPDFApp.js
1135 lines (1089 loc) · 40.8 KB
/
PDFApp.js
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
/**
* GitHub https://github.com/tanaikech/PDFApp<br>
* Library name
* @type {string}
* @const {string}
* @readonly
*/
var appName = "PDFApp";
/**
* ### Description
* Give the source PDF blob. This method is used with other methods.
*
* @param {Object} blob PDF blob.
* @return {PDFApp}
*/
function setPDFBlob(blob = null) {
if (!blob || blob.toString() != "Blob" || blob.getContentType() != MimeType.PDF) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
this.pdfBlob = blob;
return this;
}
/**
* ### Description
* When you want to use the standard font, please use this method.
* You can select one of them from the below page.
* ref: https://pdf-lib.js.org/docs/api/enums/standardfonts
* This method is used with other methods.
*
* @param {String} name Font name of the built-in standard fonts.
* @return {PDFApp}
*/
function useStandardFont(name = null) {
this.useStandardFont = name;
return this;
}
/**
* ### Description
* When you want to use the custom font, please use this method. This method is used with other methods.
*
* @param {Object} blob Blob of custom font. TTF and OTF files can be used.
* @return {PDFApp}
*/
function useCustomFont(blob = null) {
this.useCustomFont = blob;
return this;
}
/**
* ### Description
* Export specific pages from a PDF blob.
*
* @param {number[]} pageNumbers Array including the page numbers you want to export.
* @return {promise} PDF Blob including the exported pages.
*/
function exportPages(pageNumbers) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.exportPages(pdfBlob, pageNumbers);
}
/**
* ### Description
* Get PDF metadata from a PDF blob.
*
* @return {promise} PDF metadata.
*/
function getMetadata() {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.getMetadata(pdfBlob);
}
/**
* ### Description
* Update PDF metadata of a PDF blob.
*
* @param {Object} object Object for updading PDF metadata.
* @return {promise} Updated PDF blob.
*/
function udpateMetadata(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.udpateMetadata(pdfBlob, object);
}
/**
* ### Description
* Reorder pages of a PDF blob.
*
* @param {Object} object Object for reordering pages of PDF.
* @return {promise} Updated PDF blob.
*/
function reorderPages(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.reorderPages(pdfBlob, object);
}
/**
* ### Description
* Merge multiple PDF files in a single PDF.
*
* @param {Object[]} pdfBlobs Array including PDF Blobs for merging in a single PDF.
* @return {promise} Merged PDF Blob.
*/
function mergePDFs(pdfBlobs) {
if (!pdfBlobs.every(blob => blob && blob.toString() == "Blob" && blob.getContentType() == MimeType.PDF)) {
throw new Error("Please set the source PDF blobs for merging in a single PDF.");
}
const PDFA = new PDFApp(this);
return PDFA.mergePDFs(pdfBlobs);
}
/**
* ### Description
* Convert PDF pages to PNG images.
* ref: https://tanaikech.github.io/2023/01/11/converting-all-pages-in-pdf-file-to-png-images-using-google-apps-script/
*
* @return {promise} PDF Blob.
*/
function convertPDFToPng() {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.convertPDFToPng(pdfBlob);
}
/**
* ### Description
* Get values from PDF Form.
* ref: https://tanaikech.github.io/2023/08/02/retrieving-and-putting-values-for-pdf-forms-using-google-apps-script/
*
* @return {promise} Object including the values of PDF Form.
*/
function getValuesFromPDFForm() {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.getValuesFromPDFForm(pdfBlob);
}
/**
* ### Description
* Set values to PDF Form.
* ref: https://tanaikech.github.io/2023/08/02/retrieving-and-putting-values-for-pdf-forms-using-google-apps-script/
*
* @param {Object} object Object for putting values to PDF Form.
* @return {promise} Object including the values of PDF Form.
*/
function setValuesToPDFForm(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.setValuesToPDFForm(pdfBlob, object);
}
/**
* ### Description
* Create PDF Form By Google Slide template.
* ref: https://medium.com/google-cloud/creating-pdf-forms-from-google-slide-template-using-google-apps-script-cef35e7d9822
*
* @param {String} id File ID of Google Slide template.
* @param {Object} object Object for setting.
* @return {promise} Object including the values of PDF Form.
*/
function createPDFFormBySlideTemplate(id, object) {
const PDFA = new PDFApp(this);
return PDFA.createPDFFormBySlideTemplate(id, object);
}
/**
* ### Description
* Embed objects into PDF blob.
* ref: https://medium.com/google-cloud/embedding-objects-in-pdf-using-google-apps-script-ddbee857c642
*
* @param {Object} pdfBlob Blob of PDF data for embedding objects.
* @param {Object} object Object including the values for embedding objects.
* @return {promise} PDF Blob.
*/
function embedObjects(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.embedObjects(pdfBlob, object);
}
/**
* ### Description
* Insert header and/or footer into PDF blob.
*
* @param {Object} pdfBlob Blob of PDF data for embedding objects.
* @param {Object} object Object including the values for inserting header and footer.
* @return {promise} PDF Blob.
*/
function insertHeaderFooter(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.insertHeaderFooter(pdfBlob, object);
}
/**
* ### Description
* Split each page of a PDF to an individual PDF file.
*
* @return {promise} PDF Blobs.
*/
function splitPDF() {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.splitPDF(pdfBlob);
}
/**
* ### Description
* Add page numbers to PDF.
*
* @param {Object} object Object including the format of page number.
* @return {promise} PDF Blobs.
*/
function addPageNumbers(object) {
if (!this.pdfBlob) {
throw new Error("Please set the source PDF blob using the setPDFBlob method.");
}
const pdfBlob = this.pdfBlob;
const PDFA = new PDFApp(this);
return PDFA.addPageNumbers(pdfBlob, object);
}
/**
* ### Description
* This is a Class PDFApp for managing PDF using Google Apps Script.
*
* Author: Tanaike ( https://tanaikech.github.io/ )
*/
class PDFApp {
/**
* ### Description
* Constructor of this class.
*
* @return {void}
*/
constructor(e) {
this.cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js"; // or "https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"
this.cdnFontkit = "https://unpkg.com/@pdf-lib/fontkit/dist/fontkit.umd.min.js";
this.loadPdfLib_();
if (e.useCustomFont && e.useCustomFont.toString() == "Blob") {
this.loadFontkit_();
this.customFont = e.useCustomFont;
} else if (e.useStandardFont && typeof e.useStandardFont == "string") {
this.standardFont = e.useStandardFont;
}
}
/**
* ### Description
* Export specific pages from a PDF blob.
* ref: https://medium.com/google-cloud/exporting-specific-pages-from-a-pdf-as-a-new-pdf-using-google-apps-script-2f22d07b4618
*
* @param {Object} pdfBlob Blob of PDF data by retrieving with Google Apps Script.
* @param {number[]} pageNumbers Array including the page numbers you want to export.
* @return {promise} PDF Blob including the exported pages.
*/
exportPages(pdfBlob, pageNumbers) {
if (!pageNumbers || !Array.isArray(pageNumbers) || pageNumbers.length == 0) {
throw new Error("Please set the page numbers you want to export.");
}
return new Promise(async (resolve, reject) => {
try {
const pdfData = await this.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const pdfDoc = await this.PDFLib.PDFDocument.create();
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
pages.forEach((page, i) => {
if (pageNumbers.includes(i + 1)) {
pdfDoc.addPage(page);
}
});
const bytes = await pdfDoc.save();
resolve(Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`));
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Get PDF metadata from a PDF blob.
* ref: https://medium.com/google-cloud/management-of-pdf-metadata-using-google-apps-script-60fd41f4fc16
*
* @param {Object} pdfBlob Blob of PDF data by retrieving with Google Apps Script.
* @return {promise} PDF metadata.
*/
getMetadata(pdfBlob) {
return new Promise(async (resolve, reject) => {
const keys = ["title", "subject", "author", "creator", "creationDate", "modificationDate", "keywords", "producer"];
const pdfData = await this.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
try {
const metadata = keys.reduce((o, k) => ((o[k] = pdfData[`get${k.charAt(0).toUpperCase() + k.slice(1)}`]() || null), o), {});
metadata.numberOfPages = pdfData.getPageCount();
const pdfDoc = await this.PDFLib.PDFDocument.create();
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
metadata.pageInfo = pages.map((page, i) => {
const { width, height } = page.getSize();
const { x, y } = page.getPosition();
return { page: i + 1, pageWidth: width, pageHeight: height, defaultPositionX: x, defaultPositionY: y };
});
resolve(metadata);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Update PDF metadata of a PDF blob.
* ref: https://medium.com/google-cloud/management-of-pdf-metadata-using-google-apps-script-60fd41f4fc16
*
* @param {Object} pdfBlob Blob of PDF data by retrieving with Google Apps Script.
* @param {Object} object Object including the values for updating metadata.
* @return {promise} PDF Blob.
*/
udpateMetadata(pdfBlob, object) {
if (typeof object != "object" || Object.keys(object).length == 0) {
throw new Error("Please set valid object for updating PDF metadata.");
}
const self = this;
return new Promise(async (resolve, reject) => {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const keys = ["title", "subject", "author", "creator", "creationDate", "modificationDate", "keywords", "producer"];
try {
Promise.all(
keys.map((k) =>
new Promise(async (r, rj) => {
try {
if (object.hasOwnProperty(k)) {
const f = `set${k.charAt(0).toUpperCase() + k.slice(1)}`;
if (k == "title") {
await pdfData[f](...object[k]);
} else {
if (["creationDate", "modificationDate"].includes(k)) {
object[k] = new Date(object[k]);
} else if (k == "keywords") {
object[k] = JSON.parse(JSON.stringify(object[k]));
}
await pdfData[f](object[k]);
}
r("Done");
}
} catch (err) {
rj(err);
}
})
)
)
.then(async (_) => {
const bytes = await pdfData.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
})
.catch((err) => console.log(err));
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Update PDF metadata of a PDF blob.
* ref: https://medium.com/google-cloud/changing-order-of-pages-in-pdf-file-using-google-apps-script-f6b3de05d7df
*
* @param {Object} pdfBlob Blob of PDF data by retrieving with Google Apps Script.
* @param {Object} object Object including the values for reordering pages.
* @return {promise} PDF Blob.
*/
reorderPages(pdfBlob, object) {
if (typeof object != "object" || Object.keys(object).length == 0) {
throw new Error("Please set valid object for reordering PDF pages.");
}
const self = this;
return new Promise(async (resolve, reject) => {
const { newOrderOfpages, ignoreSkippedPages } = object;
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const numberOfPages = pdfData.getPageCount();
const maxPage = Math.max(...newOrderOfpages);
if (numberOfPages < maxPage || numberOfPages < newOrderOfpages.length) {
reject("Maximum page in the order of pages is over than the maximum page of the original PDF file.");
}
let skippedPages = [];
if (!ignoreSkippedPages && numberOfPages > newOrderOfpages.length) {
skippedPages = [...Array(numberOfPages)].map((_, i) => i + 1).filter(e => !newOrderOfpages.includes(e));
}
const pdfDoc = await self.PDFLib.PDFDocument.create();
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
[...newOrderOfpages, ...skippedPages].forEach(e => pdfDoc.addPage(pages[e - 1]));
const bytes = await pdfDoc.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
});
}
/**
* ### Description
* Merge multiple PDF files in a single PDF.
* ref: https://tanaikech.github.io/2023/01/10/merging-multiple-pdf-files-as-a-single-pdf-file-using-google-apps-script/
*
* @param {Object[]} pdfBlobs Array including PDF Blobs for merging in a single PDF.
* @return {promise} PDF Blob.
*/
mergePDFs(pdfBlobs) {
const self = this;
return new Promise(async (resolve, reject) => {
try {
const data = pdfBlobs.map(blob => new Uint8Array(blob.getBytes()));
const pdfDoc = await self.PDFLib.PDFDocument.create();
for (let i = 0; i < data.length; i++) {
const pdfData = await self.PDFLib.PDFDocument.load(data[i]);
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
pages.forEach(page => pdfDoc.addPage(page));
}
const bytes = await pdfDoc.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "new_PDFFile.pdf");
resolve(newBlob);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Convert PDF pages to PNG images.
* ref: https://tanaikech.github.io/2023/01/11/converting-all-pages-in-pdf-file-to-png-images-using-google-apps-script/
*
* @param {Object} pdfBlob Blob of PDF data.
* @return {promise} PDF Blob.
*/
convertPDFToPng(pdfBlob) {
const self = this;
return new Promise(async (resolve, reject) => {
try {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const pageLength = pdfData.getPageCount();
console.log(`Total pages: ${pageLength}`);
const obj = { imageBlobs: [], fileIds: [] };
const token = ScriptApp.getOAuthToken();
for (let i = 0; i < pageLength; i++) {
console.log(`Processing page: ${i + 1}`);
const pdfDoc = await self.PDFLib.PDFDocument.create();
const [page] = await pdfDoc.copyPages(pdfData, [i]);
pdfDoc.addPage(page);
const bytes = await pdfDoc.save();
const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `temp_page${i + 1}.pdf`);
const id = DriveApp.createFile(blob).getId();
Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file.
const res = UrlFetchApp.fetch(
`https://drive.google.com/thumbnail?id=${id}&sz=w1000`,
{
headers: { authorization: "Bearer " + token },
muteHttpExceptions: true
}
);
if (res.getResponseCode() != 200) {
reject(res.getContentText());
return;
}
const imageBlob = res.getBlob().setName(`page${i + 1}.png`);
obj.imageBlobs.push(imageBlob);
obj.fileIds.push(id);
}
obj.fileIds.forEach(id => DriveApp.getFileById(id).setTrashed(true));
resolve(obj.imageBlobs);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Get values from PDF Form.
* ref: https://medium.com/google-cloud/retrieving-and-putting-values-for-pdf-forms-using-google-apps-script-92412a7cf0af
*
* @param {Object} pdfBlob Blob of PDF data.
* @return {promise} Object including the values of PDF Form.
*/
getValuesFromPDFForm(pdfBlob) {
const self = this;
return new Promise(async (resolve, reject) => {
try {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const form = pdfData.getForm();
const { PDFTextField, PDFDropdown, PDFCheckBox, PDFRadioGroup } = self.PDFLib;
const obj = form.getFields().map(function (f) {
const retObj = { name: f.getName() };
if (f instanceof PDFTextField) {
retObj.value = f.getText();
retObj.type = "Textbox";
} else if (f instanceof PDFDropdown) {
retObj.value = f.getSelected();
retObj.options = f.getOptions();
retObj.type = "Dropdown";
} else if (f instanceof PDFCheckBox) {
retObj.value = f.isChecked();
retObj.type = "Checkbox";
} else if (f instanceof PDFRadioGroup) {
retObj.value = f.getSelected();
retObj.options = f.getOptions();
retObj.type = "Radiobutton";
} else {
retObj.type = "Unsupported type";
}
return retObj;
});
resolve(obj);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Set values to PDF Form.
* ref: https://medium.com/google-cloud/retrieving-and-putting-values-for-pdf-forms-using-google-apps-script-92412a7cf0af
*
* @param {Object} pdfBlob Blob of PDF data.
* @param {Object} object Object for putting values to PDF Form.
* @return {promise} Object including the values of PDF Form.
*/
setValuesToPDFForm(pdfBlob, object) {
if (!object.values || !Array.isArray(object.values)) {
throw new Error("Please set valid values.");
}
const self = this;
return new Promise(async (resolve, reject) => {
try {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const form = pdfData.getForm();
if (self.standardFont || self.customFont) {
await self.setCustomFont_(pdfData, form, { standardFont: self.standardFont, customFont: self.customFont });
}
const { PDFTextField, PDFDropdown, PDFCheckBox, PDFRadioGroup } = self.PDFLib;
for (let { name, value } of object.values) {
const field = form.getField(name);
if (field instanceof PDFTextField) {
field.setText(value);
} else if (field instanceof PDFDropdown) {
if (field.isMultiselect()) {
for (let v of value) {
field.select(v);
}
} else {
field.select(value);
}
} else if (field instanceof PDFCheckBox) {
field[value ? "check" : "uncheck"]();
} else if (field instanceof PDFRadioGroup) {
field.select(value);
}
}
const bytes = await pdfData.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
} catch (e) {
reject(e);
}
});
}
/**
* ### Description
* Create PDF Form By Google Slide template.
* ref: https://medium.com/google-cloud/creating-pdf-forms-from-google-slide-template-using-google-apps-script-cef35e7d9822
*
* @param {String} id File ID of Google Slide template.
* @param {Object} object Object for setting.
* @return {promise} Object including the values of PDF Form.
*/
createPDFFormBySlideTemplate(id, object) {
if (!id || id == "") {
throw new Error("Please set the file ID of Google Slide including the template for PDF Form.");
}
if (!object || !object.values || !Array.isArray(object.values) || object.values.length == 0) {
throw new Error("Please set valid object for creating PDF Form from Google Slide template.");
}
const self = this;
return new Promise(async (resolve, reject) => {
try {
const obj = self.getObjectFromSlide_(id, object.values);
const newBlob = await self.createFields_(self, obj);
resolve(newBlob);
} catch (e) {
reject(e);
}
});
}
/**
* ### Description
* Embed objects into PDF blob.
* ref: https://medium.com/google-cloud/embedding-objects-in-pdf-using-google-apps-script-ddbee857c642
*
* @param {Object} pdfBlob Blob of PDF data for embedding objects.
* @param {Object} object Object including the values for embedding objects.
* @return {promise} PDF Blob.
*/
embedObjects(pdfBlob, object) {
if (!object || typeof object != "object") {
throw new Error("Please an object for embeddig the objects.");
}
const self = this;
return new Promise(async (resolve, reject) => {
try {
const { updatedObject, customFontCheck } = self.updateObject_(object);
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const numberOfPages = pdfData.getPageCount();
const pdfDoc = await self.PDFLib.PDFDocument.create();
if (customFontCheck) {
self.loadFontkit_();
pdfDoc.registerFontkit(this.fontkit);
}
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
const forPage = updatedObject[`page${i + 1}`];
if (forPage) {
for (let j = 0; j < forPage.length; j++) {
const o = forPage[j];
if (o.imageFileId) {
const image = await pdfDoc[o.method](o.imageBytes);
if (o.scale) {
const updatedImage = image.scale(o.scale);
o.width = o.width || updatedImage.width;
o.height = o.height || updatedImage.height;
} else {
o.width = o.width || image.width;
o.height = o.height || image.height;
}
delete o.imageBytes;
delete o.method;
delete o.imageFileId;
delete o.scale;
page.drawImage(image, o);
} else if (o.text) {
if (o.standardFont || o.customFont) {
o.font = await pdfDoc.embedFont(o.standardFont ? this.PDFLib.StandardFonts[o.standardFont] : o.customFont);
}
page.drawText(o.text, o);
}
}
}
pdfDoc.addPage(page);
}
const bytes = await pdfDoc.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
} catch (e) {
reject(e);
}
});
}
/**
* ### Description
* Insert header and/or footer into PDF blob.
*
* @param {Object} pdfBlob Blob of PDF data for embedding objects.
* @param {Object} object Object including the values for inserting header and footer.
* @return {promise} PDF Blob.
*/
insertHeaderFooter(pdfBlob, object) {
if (!object || typeof object != "object") {
throw new Error("Please an object for embeddig the objects.");
}
let self = this;
return new Promise(async function (resolve, reject) {
try {
const pdfDoc = await self.PDFLib.PDFDocument.create();
const form = pdfDoc.getForm();
let font = null;
if (self.standardFont || self.customFont) {
await self.setCustomFont_(pdfDoc, form, { standardFont: self.standardFont, customFont: self.customFont });
font = await pdfDoc.embedFont(self.standardFont ? self.PDFLib.StandardFonts[self.standardFont] : new Uint8Array(self.customFont.getBytes()));
}
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const numberOfPages = pdfData.getPageCount();
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
const { header, footer } = object;
const headers = header ? Object.entries(header).map(([k, v]) => [`header.${k}`, v]) : [];
const footers = footer ? Object.entries(footer).map(([k, v]) => [`footer.${k}`, v]) : [];
const sortOrder = ["LEFT", "CENTER", "RIGHT"];
[footers, headers].forEach((f, _, x) => f.sort((a, b) => {
const i1 = sortOrder.findIndex(e => a[0].includes(e.toLowerCase()));
const i2 = sortOrder.findIndex(e => b[0].includes(e.toLowerCase()));
const vlen = x.length;
return (i1 > -1 ? i1 : vlen) - (i2 > -1 ? i2 : vlen);
}));
const alignObj = { "center": "Center", "left": "Left", "right": "Right" };
for (let i = 0; i < numberOfPages; i++) {
const pageNumber = i + 1;
const page = pdfDoc.addPage(pages[i]);
const pageHeight = page.getHeight();
const pageWidth = page.getWidth();
if (headers.length > 0) {
const sizeWidthHead = pageWidth / (headers.length);
for (let j = 0; j < headers.length; j++) {
const [k, v] = headers[j];
const o = {
borderWidth: v.borderWidth || 0,
x: j * sizeWidthHead,
y: pageHeight - ((v.yOffset || 0) + (v.height || 20)),
width: sizeWidthHead,
height: v.height || 30,
...v,
font,
};
await self.addHeaderFooterFields_(self, { page, form, pageNumber, k, v, o, alignObj, font });
}
}
if (footers.length > 0) {
const sizeWidthFoot = pageWidth / (footers.length);
for (let j = 0; j < footers.length; j++) {
const [k, v] = footers[j];
const o = {
borderWidth: v.borderWidth || 0,
x: j * sizeWidthFoot,
y: v.yOffset || 0,
width: sizeWidthFoot,
height: v.height || 30,
...v,
font,
};
await self.addHeaderFooterFields_(self, { page, form, pageNumber, k, v, o, alignObj, font });
}
}
}
const bytes = await pdfDoc.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
} catch (e) {
reject(e);
}
});
}
/**
* ### Description
* Split each page of a PDF to an individual PDF file.
*
* @param {Object} pdfBlob Blob of PDF data.
* @return {promise} PDF Blob.
*/
splitPDF(pdfBlob) {
const self = this;
return new Promise(async (resolve, reject) => {
try {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const pageLength = pdfData.getPageCount();
console.log(`Total pages: ${pageLength}`);
const pdfBlobs = [];
for (let i = 0; i < pageLength; i++) {
console.log(`Processing page: ${i + 1}`);
const pdfDoc = await self.PDFLib.PDFDocument.create();
const [page] = await pdfDoc.copyPages(pdfData, [i]);
pdfDoc.addPage(page);
const bytes = await pdfDoc.save();
const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `page${i + 1}.pdf`);
pdfBlobs.push(blob);
}
resolve(pdfBlobs);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Add page numbers to PDF.
*
* @param {Object} pdfBlob Blob of PDF data.
* @param {Object} object Object including the format of page number.
* @return {promise} PDF Blobs.
*/
addPageNumbers(pdfBlob, object) {
if (!object || typeof object != "object" || !["size", "x", "y"].every(e => e in object)) {
throw new Error("Please an object for adding page numbers.");
}
const self = this;
return new Promise(async (resolve, reject) => {
try {
const pdfData = await self.getPDFObjectFromBlob_(pdfBlob).catch(err => reject(err));
const pdfDoc = await self.PDFLib.PDFDocument.create();
(await pdfDoc.copyPages(pdfData, pdfData.getPageIndices()))
.forEach((page, i) => {
if (isNaN(object.x)) {
const { width } = page.getSize();
const obj = { center: width / 2, left: 20, right: width - 20 };
const pageFormatObj = { ...object };
pageFormatObj.x = obj[object.x];
page.drawText(`${i + 1}`, pageFormatObj);
} else {
page.drawText(`${i + 1}`, object);
}
pdfDoc.addPage(page);
});
const bytes = await pdfDoc.save();
const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${pdfBlob.getName()}`);
resolve(newBlob);
} catch (err) {
reject(err);
}
});
}
/**
* ### Description
* Create fields of PDF Form.
*
* @param {Object} self this of this Class object.
* @param {Object} object Object for creating fields.
* @return {Object} Blob of new PDF.
*/
addHeaderFooterFields_(self, object) {
const { page, form, pageNumber, k, v, o, alignObj, font } = object;
const fieldName = `${k}.${pageNumber}`;
const textBox = form.createTextField(fieldName);
if (v.text) {
textBox.setText(v.text);
}
if (v.alignment) {
textBox.setAlignment(self.PDFLib.TextAlignment[alignObj[v.alignment.toLowerCase()]]);
}
textBox.disableScrolling();
textBox.disableMultiline();
textBox.enableReadOnly();
["x", "y", "width", "text"].forEach(e => delete v[e]);
textBox.addToPage(page, o);
}
/**
* ### Description
* Create fields of PDF Form.
*
* @param {Object} self this of this Class object.
* @param {Object} object Object for creating fields.
* @return {Object} Blob of new PDF.
*/
async createFields_(self, object) {
const { obj, blob } = object;
const pdfDoc = await self.PDFLib.PDFDocument.create();
const form = pdfDoc.getForm();
if (self.standardFont || self.customFont) {
await self.setCustomFont_(pdfDoc, form, { standardFont: self.standardFont, customFont: self.customFont });
}
const pdfData = await self.getPDFObjectFromBlob_(blob).catch(err => reject(err));
const numberOfPages = pdfData.getPageCount();
const pages = await pdfDoc.copyPages(pdfData, pdfData.getPageIndices());
const xAxisOffset = 0.5;
const yAxisOffset = 0.5;
for (let i = 0; i < numberOfPages; i++) {
const pageNumber = i + 1;
const page = pdfDoc.addPage(pages[i]);
const pageHeight = page.getHeight();
const yOffset = pageHeight;
obj[i].forEach((v, k) => {
if (k == "checkbox") {
v.forEach(t => {
t.forEach(u => {
const checkbox = form.createCheckBox(u.title);
checkbox.addToPage(page, { x: u.leftOffset - xAxisOffset, y: yOffset - u.topOffset - u.height + yAxisOffset, width: u.width, height: u.height });
self.setStyles_(checkbox, u);
});
});
} else if (k == "radiobutton") {
v.forEach((t, kk) => {
const radio = form.createRadioGroup(`radiobutton.${kk}.page${pageNumber}`);
t.forEach(u => {
radio.addOptionToPage(u.title, page, { x: u.leftOffset - xAxisOffset, y: yOffset - u.topOffset - u.height + yAxisOffset, width: u.width, height: u.height });
self.setStyles_(radio, u);
});
});
} else if (k == "textbox") {
v.forEach(t => {
t.forEach(u => {
const textBox = form.createTextField(u.title);
textBox.addToPage(page, {
x: u.leftOffset - xAxisOffset,
y: yOffset - u.topOffset - u.height + yAxisOffset,
width: u.width,
height: u.height,
});
self.setStyles_(textBox, u);
});
});
} else if (k == "dropdownlist") {
v.forEach(t => {
t.forEach(u => {
const drowdown = form.createDropdown(u.title);
drowdown.addToPage(page, {
x: u.leftOffset - xAxisOffset,
y: yOffset - u.topOffset - u.height + yAxisOffset,
width: u.width,
height: u.height
});
self.setStyles_(drowdown, u);
});
});
}
});
}
const bytes = await pdfDoc.save();
return Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `new_${blob.getName()}`);
}
/**
* ### Description
* Set custom font to PDF form.
*
* @param {Object} pdfDoc Object of PDF document.
* @param {Object} form Object of PDF form.
* @return {void}
*/
async setCustomFont_(pdfDoc, form, { standardFont, customFont }) {
let customfont;
if (standardFont) {
customfont = await pdfDoc.embedFont(this.PDFLib.StandardFonts[standardFont]);
} else if (customFont) {
pdfDoc.registerFontkit(this.fontkit);
customfont = await pdfDoc.embedFont(new Uint8Array(customFont.getBytes()));
}
// Ref: https://github.com/Hopding/pdf-lib/issues/1152
const rawUpdateFieldAppearances = form.updateFieldAppearances.bind(form);
form.updateFieldAppearances = function () {
return rawUpdateFieldAppearances(customfont);
};
}
/**
* ### Description
* Set styles to the field of PDF form.
*
* @param {Object} instance Instance of field.
* @param {Object} u Methods and values for setting the styles.
* @return {Object} Object for creating the fields of PDF Form.
*/
setStyles_(instance, u) {
if (u.description.methods && u.description.methods.length > 0) {
u.description.methods.forEach(({ method, value }) => {
if (value && Array.isArray(value)) {
value = [...value];
}
instance[method](value || null)
});
}
}
/**
* ### Description
* Get an object for creating the fields of PDF Form from Google Slide.
*
* @param {String} id File ID of Google Slide template.
* @return {Object} Object for creating the fields of PDF Form.
*/
getObjectFromSlide_(id, object) {