forked from asciidoctor/asciidoctor-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exportAsPDF.ts
264 lines (237 loc) · 10.7 KB
/
exportAsPDF.ts
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
import * as vscode from 'vscode'
import * as os from 'os'
import * as fs from 'fs'
import * as path from 'path'
import { exec, spawn } from 'child_process'
import { uuidv4 } from 'uuid'
import * as zlib from 'zlib'
import { AsciidocEngine } from '../asciidocEngine'
import { Command } from '../commandManager'
import url = require('url')
import { Logger } from '../logger'
export class ExportAsPDF implements Command {
public readonly id = 'asciidoc.exportAsPDF'
constructor (private readonly engine: AsciidocEngine, private readonly logger: Logger) {
this.engine = engine
this.logger = logger
}
public async execute () {
const editor = vscode.window.activeTextEditor
if (editor === null || editor === undefined) { return }
const doc = editor.document
const sourceName = path.parse(path.resolve(doc.fileName))
const pdfFilename = vscode.Uri.file(path.join(sourceName.root, sourceName.dir, sourceName.name + '.pdf'))
const text = doc.getText()
if (vscode.workspace.getConfiguration('asciidoc', null).get('use_asciidoctorpdf')) {
const docPath = path.parse(path.resolve(doc.fileName))
let pdfPath = ''
const pdfUri = await vscode.window.showSaveDialog({ defaultUri: pdfFilename })
if (!(pdfUri === null || pdfUri === undefined)) {
pdfPath = pdfUri.fsPath
} else {
console.error(`ERROR: invalid pdfUri "${pdfUri}"`)
return
}
const asciidoctorPDFCommand = vscode.workspace
.getConfiguration('asciidoc', null)
.get('asciidoctorPDFCommand', 'asciidoctor-pdf')
const adocPDFCmdArray = asciidoctorPDFCommand
.split(/(\s+)/)
.filter(function (e) { return e.trim().length > 0 })
const adocPDFCmd = adocPDFCmdArray[0]
const adocPDFCmdArgs = adocPDFCmdArray.slice(1)
adocPDFCmdArgs.push('-q', '-B', '"' + docPath.dir.replace('"', '\\"') + '"',
'-o', '"' + pdfPath.replace('"', '\\"') + '"', '-')
const options = { shell: true, cwd: docPath.dir }
const asciidoctorPDF = spawn(adocPDFCmd, adocPDFCmdArgs, options)
asciidoctorPDF.stderr.on('data', (data) => {
let errorMessage = data.toString()
errorMessage += '\n'
errorMessage += 'command: ' + adocPDFCmd + ' ' + adocPDFCmdArgs.join(' ')
errorMessage += '\n'
errorMessage += 'If the asciidoctor-pdf binary is not in your PATH, you can set the full path.'
errorMessage += 'Go to `File -> Preferences -> User settings` and adjust the asciidoc.asciidoctorPDFCommand'
console.error(errorMessage)
vscode.window.showErrorMessage(errorMessage)
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
asciidoctorPDF.on('close', (code) => {
offerOpen(pdfPath)
})
asciidoctorPDF.stdin.write(text)
asciidoctorPDF.stdin.end()
} else {
const wkHTMLtoPDFPath = vscode.workspace
.getConfiguration('asciidoc')
.get('wkHTMLtoPDFPath', '')
const { output: html, document } = await this.engine.render(doc.uri, true, text, false, 'html5')
const showTitlePage = document?.getAttribute('showTitlePage')
const author = document?.getAttribute('author')
const email = document?.getAttribute('email')
const doctitle: string | undefined = document?.getAttribute('doctitle')
const titlePageLogo: string | undefined = document?.getAttribute('titlePageLogo')
const footerCenter: string | undefined = document?.getAttribute('footer-center')
let cover: string | undefined
let imageHTML: string = ''
if (!(showTitlePage === null)) {
if (!(titlePageLogo === null)) {
const imageURL = titlePageLogo.startsWith('http') ? titlePageLogo : path.join(sourceName.dir, titlePageLogo)
imageHTML = (titlePageLogo === null) ? '' : `<img src="${imageURL}">`
}
const tmpFilePath = path.join(os.tmpdir(), uuidv4() + '.html')
const extensionContext = vscode.extensions.getExtension('asciidoctor.asciidoctor-vscode')
const styleHref = vscode.Uri.joinPath(extensionContext.extensionUri, 'media', 'all-centered.css')
const html = `\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="${styleHref}">
</head>
<body>
<div class="outer">
<div class="middle">
<div class="inner">
${imageHTML}
<h1>${doctitle}</h1>
<p>${author} <${email}></p>
</div>
</div>
</div>
</body>
</html>
`
fs.writeFileSync(tmpFilePath, html, 'utf-8')
cover = `cover ${tmpFilePath}`
}
const platform = process.platform
const ext = platform === 'win32' ? '.exe' : ''
const arch = process.arch
let binaryPath = path.resolve(path.join(__dirname, 'wkhtmltopdf-' + platform + '-' + arch + ext))
if (wkHTMLtoPDFPath !== '') { binaryPath = wkHTMLtoPDFPath }
if (!fs.existsSync(binaryPath)) {
const label = await vscode.window.showInformationMessage('This feature requires wkhtmltopdf\ndo you want to download', 'Download')
if (label !== 'Download') { return }
await vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: 'Downloading wkhtmltopdf',
// cancellable: true
}, async (progress) => {
progress.report({ message: 'Downloading wkhtmltopdf...' })
const downloadURL = `https://github.com/joaompinto/wkhtmltopdf/releases/download/v0.0.1/wkhtmltopdf-${platform}-${arch}${ext}.gz`
this.logger.log('Downloading ' + downloadURL)
await downloadFile(downloadURL, binaryPath + '.gz', progress).then(() => {
progress.report({ message: 'Unzipping wkhtmltopdf...' })
const ungzip = zlib.createGunzip()
const inp = fs.createReadStream(binaryPath + '.gz')
const out = fs.createWriteStream(binaryPath)
inp.pipe(ungzip).pipe(out)
fs.chmodSync(binaryPath, 0x755)
}).catch(async (reason) => {
binaryPath = null
console.error('Error downloading', downloadURL, ' ', reason)
await vscode.window.showErrorMessage('Error installing wkhtmltopdf, ' + reason.toString())
})
})
if (binaryPath === null || binaryPath === undefined) { return }
}
const saveFilename = await vscode.window.showSaveDialog({ defaultUri: pdfFilename })
if (!(saveFilename === null || saveFilename === undefined)) {
await html2pdf(html, binaryPath, cover, footerCenter, saveFilename.fsPath)
.then((result) => { offerOpen(result) })
.catch((reason) => {
console.error('Got error', reason)
vscode.window.showErrorMessage('Error converting to PDF, ' + reason.toString())
})
}
}
}
}
async function downloadFile (downloadURL: string, filename: string, progress) {
// load "follow-redirects" only when needed (because this module cannot be loaded in a browser environment)
const followRedirects = await import('follow-redirects')
return new Promise((resolve, reject) => {
const downloadOptions = url.parse(downloadURL)
const wstream = fs.createWriteStream(filename)
let totalDownloaded = 0
// Proxy support needs to be reworked
// var proxy = process.env.http_proxy || vscode.workspace.getConfiguration("http", null)["proxy"].trim();
// var proxyStrictSSL = vscode.workspace.getConfiguration("http", null)["proxyStrictSSL"];
// if (proxy != '')
// {
// var agent = new HttpsProxyAgent(proxy);
// downloadOptions.agent = agent
// downloadOptions.rejectUnauthorized = proxyStrictSSL
// }
followRedirects.https.get(downloadOptions, (resp) => {
const contentSize = resp.headers['content-length']
if (resp.statusCode !== 200) {
wstream.end()
fs.unlinkSync(filename)
return reject(new Error('http error' + resp.statusCode))
}
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
totalDownloaded += chunk.length
progress.report({ message: 'Downloading wkhtmltopdf ... ' + ((totalDownloaded / contentSize) * 100.0).toFixed(0) + '%' })
wstream.write(chunk)
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
wstream.end()
resolve()
})
}).on('error', (err) => {
console.error('Error: ' + err.message)
reject(err.message)
})
})
}
function offerOpen (destination) {
// Saving the JSON that represents the document to a temporary JSON-file.
vscode.window.showInformationMessage(('Successfully converted to ' + path.basename(destination)), 'Open File').then((label: string) => {
if (label === 'Open File') {
switch (process.platform) {
// Use backticks for unix systems to run the open command directly
// This avoids having to wrap the command AND path in quotes which
// breaks if there is a single quote (') in the path
case 'win32':
exec(`"${destination.replace('"', '\\"')}"`)
break
case 'darwin':
exec(`\`open "${destination.replace('"', '\\"')}" ; exit\``)
break
case 'linux':
exec(`\`xdg-open "${destination.replace('"', '\\"')}" ; exit\``)
break
default:
vscode.window.showWarningMessage('Output type is not supported')
break
}
}
})
}
export async function html2pdf (html: string, binaryPath: string, cover: string, footerCenter: string, filename: string) {
const documentPath = path.dirname(filename)
return new Promise((resolve, reject) => {
const options = { cwdir: documentPath, stdio: ['pipe', 'ignore', 'pipe'] }
let cmdArguments = ['--encoding', ' utf-8', '--javascript-delay', '1000']
if (footerCenter !== null) {
cmdArguments = cmdArguments.concat(['--footer-center', footerCenter])
}
if (cover !== null && cover !== undefined) {
cmdArguments = cmdArguments.concat(cover.split(' '))
}
cmdArguments = cmdArguments.concat(['-', filename])
const command = spawn(binaryPath, cmdArguments, options)
let errorData = ''
command.stdin.write(html)
command.stdin.end()
command.stderr.on('data', (data) => {
errorData += data
})
command.on('close', (code) => {
if (code === 0) { resolve(filename) } else { reject(errorData) }
})
})
}