1
+ import credentials from "../../../Credentials/credentials.json" with { type : "json" } ; // json-file in this format: { "id": "*****", "key": "*******" }
2
+ import fs from 'node:fs/promises' ;
3
+ import path from 'node:path' ;
4
+ import { PdfApi } from "../../src/api/api.js" ;
5
+ import { OptimizeOptions } from "../../src/models/optimizeOptions.js" ;
6
+
7
+ const configParams = {
8
+ LOCAL_FOLDER : "C:\\Samples\\" ,
9
+ PDF_DOCUMENT_NAME : "sample.pdf" ,
10
+ TEMP_FOLDER : 'TempPdfCloud' ,
11
+ LOCAL_RESULT_DOCUMENT_NAME : "output_sample.pdf" ,
12
+ } ;
13
+
14
+ const pdfApi = new PdfApi ( credentials . id , credentials . key ) ;
15
+
16
+ const PdfCompress = {
17
+ async uploadDocument ( fileName , localFolder ) {
18
+ const fileNamePath = path . join ( configParams . LOCAL_FOLDER , configParams . PDF_DOCUMENT_NAME ) ;
19
+ const fileData = await fs . readFile ( fileNamePath ) ;
20
+ const storagePath = path . join ( configParams . TEMP_FOLDER , configParams . PDF_DOCUMENT_NAME ) ;
21
+ await pdfApi . uploadFile ( storagePath , fileData )
22
+ . then ( ( ) => console . log ( "File: '" + configParams . PDF_DOCUMENT_NAME + "' successfully uploaded." ) ) ;
23
+ } ,
24
+
25
+ async downloadResult ( ) {
26
+ const fileName = path . join ( configParams . TEMP_FOLDER , configParams . PDF_DOCUMENT_NAME ) ;
27
+ const changedPdfData = await pdfApi . downloadFile ( fileName ) ;
28
+ const filePath = path . join ( configParams . LOCAL_FOLDER , configParams . LOCAL_RESULT_DOCUMENT_NAME ) ;
29
+ await fs . writeFile ( filePath , changedPdfData . body ) ;
30
+ console . log ( "Downloaded: " + filePath ) ;
31
+ } ,
32
+
33
+ async compressPdfDocument ( ) {
34
+ if ( pdfApi ) {
35
+
36
+ const optimizeOptions = new OptimizeOptions ( ) ;
37
+ optimizeOptions . allowReusePageContent = true ;
38
+ optimizeOptions . compressImages = true ;
39
+ optimizeOptions . imageQuality = 100 ;
40
+ optimizeOptions . linkDuplcateStreams = true ;
41
+ optimizeOptions . removeUnusedObjects = true ;
42
+ optimizeOptions . removeUnusedStreams = true ;
43
+ optimizeOptions . unembedFonts = true ;
44
+
45
+ const response = await pdfApi . postOptimizeDocument ( configParams . PDF_DOCUMENT_NAME , optimizeOptions , null , configParams . TEMP_FOLDER ) ;
46
+ if ( response . body . code != 200 )
47
+ console . error ( "compressPdfDocument(): Failed to compress the PDF document!" ) ;
48
+ else
49
+ console . log ( "compressPdfDocument(): Successfully copressed the PDF document '" + configParams . PDF_DOCUMENT_NAME + "' !" ) ;
50
+ }
51
+ } ,
52
+ } ;
53
+
54
+ async function main ( ) {
55
+ try {
56
+ await PdfCompress . uploadDocument ( ) ;
57
+ await PdfCompress . compressPdfDocument ( ) ;
58
+ await PdfCompress . downloadResult ( ) ;
59
+
60
+ } catch ( error ) {
61
+ console . error ( "Error:" , error . message ) ;
62
+ }
63
+ }
64
+
65
+ main ( ) ;
0 commit comments