-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathhtmlToPdf.ts
More file actions
335 lines (302 loc) · 11.7 KB
/
Copy pathhtmlToPdf.ts
File metadata and controls
335 lines (302 loc) · 11.7 KB
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
import { renderToString } from 'react-dom/server';
import { compiler } from 'markdown-to-jsx';
import htmlToPdfmake from 'html-to-pdfmake';
import pdfMake from 'pdfmake/build/pdfmake';
import { Content, ImageDefinition, TDocumentDefinitions } from 'pdfmake/interfaces';
import { FintelDesign } from '@components/common/form/FintelDesignField';
import { APP_BASE_PATH } from '../../relay/environment';
import { capitalizeWords } from '../String';
import logoWhite from '../../static/images/logo_text_white.png';
import { getBase64ImageFromURL, isImageFromUrlSvg } from '../Image';
import { FONTS, detectLanguage } from './utils/pdfFonts';
import determineOrientation from './utils/pdfOrientation';
import setImagesWidth from './utils/pdfImageWidth';
import setTableFullWidth, { defaultTableLayout, getMaxTableColumnCount, VERY_WIDE_TABLE_COLUMN_THRESHOLD, WIDE_TABLE_COLUMN_THRESHOLD } from './utils/pdfTableWidth';
import addPageBreaks, { pdfPageBreaks } from './utils/pdfPageBreaks';
import removeUnnecessaryHtml from './utils/pdfUnnecessarytHtml';
import pdfBackground from './utils/pdfBackground';
import pdfHeader from './utils/pdfHeader';
import pdfFooter from './utils/pdfFooter';
import { DARK, DARK_BLUE, GREY, WHITE } from './utils/constants';
import { dateFormat } from '../Time';
type PdfPageSize = 'A4' | 'A3';
type PdfPageOrientation = 'portrait' | 'landscape';
const PDF_PAGE_DIMENSIONS: Record<PdfPageSize, { width: number; height: number }> = {
A4: { width: 595.28, height: 841.89 },
A3: { width: 841.89, height: 1190.55 },
};
export const resolvePdfPageGeometry = (
pageSize: PdfPageSize,
pageOrientation: PdfPageOrientation,
) => {
const dimensions = PDF_PAGE_DIMENSIONS[pageSize];
const pageWidth = pageOrientation === 'landscape' ? dimensions.height : dimensions.width;
const pageHeight = pageOrientation === 'landscape' ? dimensions.width : dimensions.height;
const backPageLogoMarginTop = Math.max(120, Math.round((pageHeight - 133) / 2));
return { pageWidth, pageHeight, backPageLogoMarginTop };
};
/**
* NOT MEANT FOR EXPORT
*
* Generate a PDF that can be downloaded.
*
* @param pdfMakeObject Definition of the PDF to generate.
* @param checkOrientation True if check content to determine PDF orientation.
* @returns PDF ready to be downloaded.
*/
const generatePdf = (
pdfMakeObject: TDocumentDefinitions,
checkOrientation = false,
) => {
const docDefinition = { ...pdfMakeObject };
if (checkOrientation) {
docDefinition.pageOrientation = determineOrientation();
}
pdfMake.setTableLayouts(defaultTableLayout);
pdfMake.setFonts(FONTS);
return pdfMake.createPdf(docDefinition);
};
/**
* Transform html file into a PDF that can be downloaded.
*
* @param fileName name of the file to transform.
* @param content The content of the file.
* @returns PDF object ready to be downloaded.
*/
export const htmlToPdf = (
fileName: string,
content: string,
) => {
let htmlData = removeUnnecessaryHtml(content);
htmlData = setImagesWidth(htmlData);
// Improve render for markdown files.
if (fileName && fileName.endsWith('.md')) {
htmlData = renderToString(compiler(htmlData, { wrapper: null }));
}
htmlData = setTableFullWidth(htmlData);
// Detect CJK characters and pick a font that has CJK glyphs.
// Roboto (the pdfmake default) has no CJK glyphs, so Japanese/Korean text
// would otherwise be garbled in the exported PDF. See issue #15624.
const selectedFont = detectLanguage(htmlData);
// Transform html string into a JS object that lib pdfmake can understand.
const pdfMakeObject = htmlToPdfmake(htmlData, {
imagesByReference: true,
ignoreStyles: ['font-family'], // Ignoring fonts to force Roboto later.
defaultStyles: {
th: { bold: true, fillColor: '', font: selectedFont },
td: { font: selectedFont },
},
}) as unknown as TDocumentDefinitions; // Because wrong type when using imagesByReference: true.
pdfMakeObject.images = normalizePdfMakeImageReferences(
pdfMakeObject.images,
resolvedEntityBaseUrl,
);
pdfMakeObject.defaultStyle = {
...(pdfMakeObject.defaultStyle ?? {}),
font: selectedFont,
};
return generatePdf(pdfMakeObject, false);
};
/**
* Part to handle the embedded images of a file
*/
const normalizeEntityBaseUrl = (url: string) =>
url
.replace(/\/content\/?$/, '')
.replace(/\/$/, '');
const entityBaseUrl = `${window.location.origin}${window.location.pathname}`.replace(/\/$/, '');
const resolvedEntityBaseUrl = normalizeEntityBaseUrl(entityBaseUrl);
const resolvePdfImageUrl = (rawUrl: string, baseUrl: string) => {
if (/^https?:\/\//i.test(rawUrl) || rawUrl.startsWith('data:')) return rawUrl;
if (rawUrl.startsWith('//')) return `${window.location.protocol}${rawUrl}`;
if (rawUrl.startsWith('/')) return `${window.location.origin}${rawUrl}`;
if (rawUrl.startsWith('storage/')) return `${window.location.origin}/${rawUrl}`;
if (APP_BASE_PATH && rawUrl.startsWith(APP_BASE_PATH)) {
return `${window.location.origin}${rawUrl}`;
}
return `${baseUrl}/${rawUrl.replace(/^\/+/, '')}`;
};
const normalizePdfMakeImageReferences = (
images: TDocumentDefinitions['images'],
baseUrl: string,
): Record<string, string | ImageDefinition> => {
if (!images) return {};
return Object.fromEntries(
Object.entries(images).map(([key, value]) => {
const strValue = typeof value === 'string' ? value : null;
if (!strValue || strValue.startsWith('embedded/')) return [key, value] as const;
return [key, resolvePdfImageUrl(strValue, baseUrl)] as const;
}),
);
};
export const resolvePdfMakeEmbeddedImages = async (
images: TDocumentDefinitions['images'],
resolvedEntityBaseUrl: string,
): Promise<Record<string, string | ImageDefinition>> => {
if (!images) return {};
const entries = await Promise.all(
Object.entries(images).map(async ([key, value]) => {
const strValue = typeof value === 'string' ? value : null;
if (!strValue?.startsWith('embedded/')) return [key, value] as const;
const fileName = strValue.slice('embedded/'.length);
const url = `${resolvedEntityBaseUrl}/embedded/${encodeURIComponent(fileName)}`;
const img = await getBase64ImageFromURL(url);
const resolved = img.startsWith('data:') ? img : `data:image/png;base64,${img}`;
return [key, resolved] as const;
}),
);
return Object.fromEntries(entries);
};
/**
* Transform html file into a PDF that can be downloaded.
* /!\ Used for outcome templates reports.
*
* @param reportName Name the report outcome should have.
* @param content HTML content.
* @param templateName Name of the template used for PDF generation.
* @param markingNames Markings of the outcome report.
* @param fintelDesign Design of the template, optionally enriched with page options
* @returns PDF object ready to be downloaded.
*/
export const htmlToPdfReport = async (
reportName: string,
content: string,
templateName: string,
markingNames: string[],
fintelDesign?: FintelDesign | null | undefined,
pageOptions?: {
includeCoverPage?: boolean;
includeBackPage?: boolean;
},
) => {
const formattedTemplateName = capitalizeWords(templateName);
let logo;
let isLogoSvg = false;
if (fintelDesign?.file_id) {
const url = `${APP_BASE_PATH}/storage/view/${encodeURIComponent(
fintelDesign?.file_id,
)}`;
const { isSvg, content: svgContent } = await isImageFromUrlSvg(url);
isLogoSvg = isSvg;
if (!isLogoSvg) logo = await getBase64ImageFromURL(url);
else logo = svgContent;
}
if (!logo) {
logo = await getBase64ImageFromURL(logoWhite);
}
let htmlData = removeUnnecessaryHtml(content);
htmlData = setImagesWidth(htmlData);
const maxTableColumnCount = getMaxTableColumnCount(htmlData);
const containsWideTable = maxTableColumnCount >= WIDE_TABLE_COLUMN_THRESHOLD;
const containsVeryWideTable = maxTableColumnCount >= VERY_WIDE_TABLE_COLUMN_THRESHOLD;
const pageSize: PdfPageSize = containsVeryWideTable ? 'A3' : 'A4';
const pageOrientation: PdfPageOrientation = containsWideTable ? 'landscape' : 'portrait';
const { pageWidth, pageHeight, backPageLogoMarginTop } = resolvePdfPageGeometry(pageSize, pageOrientation);
const pageMargins: [number, number] = containsVeryWideTable ? [8, 12] : containsWideTable ? [10, 20] : [20, 30];
htmlData = setTableFullWidth(htmlData, pageWidth - 2 * pageMargins[0]);
htmlData = addPageBreaks(htmlData);
const selectedFont = detectLanguage(htmlData);
// Transform html string into a JS object that lib pdfmake can understand.
const pdfMakeObject = htmlToPdfmake(htmlData, {
removeExtraBlanks: true,
imagesByReference: true,
ignoreStyles: ['font-family'], // Ignoring fonts to force Roboto later.
defaultStyles: {
h1: { margin: [0, 20, 0, 10], color: DARK, fontSize: 32 },
h2: { margin: [0, 20, 0, 10], color: DARK, fontSize: 28 },
h3: { margin: [0, 20, 0, 10], color: DARK, fontSize: 24 },
th: { bold: true, fillColor: '', font: selectedFont },
td: { font: selectedFont },
},
}) as unknown as TDocumentDefinitions; // Because wrong type when using imagesByReference: true.
const resolvedImages = entityBaseUrl && pdfMakeObject.images
? await resolvePdfMakeEmbeddedImages(
pdfMakeObject.images,
resolvedEntityBaseUrl,
)
: pdfMakeObject.images;
const normalizedImages = normalizePdfMakeImageReferences(
resolvedImages,
resolvedEntityBaseUrl,
);
const linearGradiant = [
fintelDesign?.gradiantFromColor || DARK,
fintelDesign?.gradiantToColor || DARK_BLUE,
];
const textColor = fintelDesign?.textColor || WHITE;
const includeCoverPage = pageOptions?.includeCoverPage ?? true;
const includeBackPage = pageOptions?.includeBackPage ?? true;
const coverPage: Content[] = [
{
columns: [
isLogoSvg
? { svg: logo, width: 133 }
: { image: logo, width: 133 },
{
text: dateFormat(new Date()) ?? '',
alignment: 'right',
style: ['colorWhite'],
},
],
},
{
text: reportName,
style: ['colorWhite', selectedFont, 'textXl'],
marginTop: 200,
},
{
text: formattedTemplateName,
style: ['colorWhite', 'textMd'],
marginTop: 10,
pageBreak: 'after',
},
];
const backPage: Content[] = [
{
pageBreak: 'before',
absolutePosition: { x: 0, y: 0 },
canvas: [{
type: 'rect',
x: 0,
y: 0,
w: pageWidth,
h: pageHeight,
linearGradient: linearGradiant,
}],
},
...(isLogoSvg
? [{ svg: logo, width: 133, alignment: 'center' as const, margin: [0, backPageLogoMarginTop, 0, 0] as [number, number, number, number] }]
: [{ image: logo, width: 133, alignment: 'center' as const, margin: [0, backPageLogoMarginTop, 0, 0] as [number, number, number, number] }]
),
];
const docDefinition: TDocumentDefinitions = {
pageMargins,
pageSize,
pageOrientation,
styles: {
colorWhite: { color: textColor },
colorLight: { color: GREY },
textMd: { fontSize: 14 },
textXl: { fontSize: 40 },
fontGeo: { font: 'Geologica' },
},
defaultStyle: {
font: selectedFont,
fontSize: 12,
},
...pdfMakeObject,
images: normalizedImages,
content: [
...(includeCoverPage ? coverPage : []),
{
stack: pdfMakeObject.content as Content[],
},
...(includeBackPage ? backPage : []),
] as Content[],
background: pdfBackground(linearGradiant, { hasCoverPage: includeCoverPage }),
header: pdfHeader(linearGradiant, { hasCoverPage: includeCoverPage, hasBackPage: includeBackPage }),
footer: pdfFooter(markingNames, { hasCoverPage: includeCoverPage, hasBackPage: includeBackPage }),
pageBreakBefore: pdfPageBreaks,
};
return generatePdf(docDefinition, false);
};