-
Notifications
You must be signed in to change notification settings - Fork 0
/
generatePdf.web.js
81 lines (65 loc) · 1.82 KB
/
generatePdf.web.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
//Place this code in your backend code files. Backend code is accessed via the side menu by clicking on the curly braces then packages and apps > Backend
import { Permissions, webMethod } from "wix-web-module";
import { mediaManager } from 'wix-media-backend';
const PDFDocument = require('pdfkit')
export const generateDownloadLink = webMethod(
Permissions.Anyone,
async (fileName) => {
try {
const buffer = await generatePdf()
const file = await uploadFile(fileName,buffer)
const link = await getDownload(file)
return link
} catch (error) {
console.error("generate download error: ", error)
}
}
);
async function generatePdf(){
try {
const doc = new PDFDocument()
const chunks = []
// Collect data chunks
doc.on('data', chunk => {
chunks.push(chunk)
});
doc.text("Hello, world!", 100, 100);
doc.end();
// Convert chunks to a Buffer
await new Promise(resolve => {
doc.on('end', () => {
resolve()
});
});
const pdfBuffer = Buffer.concat(chunks)
return pdfBuffer
} catch (error) {
console.error("An error has occured: ", error)
}
}
async function uploadFile(fileName, buffer){
try {
let pdf = fileName + ".pdf"
const importedFile = mediaManager.upload(
"/UserUploads",
buffer,
pdf, {
"mediaOptions": {
"mimeType": "application/pdf",
"mediaType": "document"
}
}
)
return importedFile
} catch (error) {
console.error("Upload file error: ", error)
}
}
async function getDownload(file){
try {
const downloadLink = await mediaManager.getDownloadUrl(file.fileUrl)
return downloadLink
} catch (error) {
console.error("Error in getDownload", error)
}
}