hdoc-tools 0.9.49 → 0.9.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hdoc-build-pdf.js CHANGED
@@ -1,173 +1,173 @@
1
- (function () {
2
- 'use strict';
3
-
4
- const axios = require('axios'),
5
- cheerio = require('cheerio'),
6
- fs = require('fs-extra'),
7
- mime = require('mime-types'),
8
- path = require('path'),
9
- hdoc = require(path.join(__dirname, 'hdoc-module.js'));
10
-
11
- let hb_logo = '',
12
- footer = '',
13
- header = '';
14
-
15
- const get_footer = function (template_path) {
16
- let footer_content = null;
17
- try {
18
- footer_content = fs.readFileSync(path.join(template_path, 'template-footer.html'), 'utf8');
19
- } catch (err) {
20
- console.log(`Error loading template: ${err}`);
21
- }
22
- return footer_content;
23
- };
24
-
25
- const get_header = function (template_path) {
26
- let header_content = null;
27
- try {
28
- header_content = fs.readFileSync(path.join(template_path, 'template-header.html'), 'utf8');
29
- } catch (err) {
30
- console.log(`Error loading template: ${err}`);
31
- }
32
- return header_content;
33
- };
34
-
35
- exports.process_images = async function (file_path, html_source, verbose) {
36
- const book_work_root = file_path.path.replace(file_path.relativePath, '');
37
- if (verbose) console.log('Parsing img tags from HTML source');
38
-
39
- // Use cheerio to parse html
40
- const $ = cheerio.load(html_source);
41
-
42
- // Get iFrames from HTML, to replace with a tags
43
- let iframes = [];
44
- const iframe_html = $('iframe').map(function () {
45
- const response = {
46
- html: $.html(this),
47
- src: $(this).attr('src'),
48
- title: $(this).attr('title') ? $(this).attr('title') : 'No Link Title Provided'
49
- };
50
- return response;
51
- }).get();
52
- iframes.push(...iframe_html);
53
- for (let i = 0; i < iframes.length; i++) {
54
- const link = `<p><a href="${iframes[i].src}">${iframes[i].title}</a></p>`;
55
- const regex = new RegExp(`<iframe.*src="${iframes[i].src.replace('/', '\\/')}".*</iframe>`);
56
- html_source = html_source.replace(regex, link);
57
- }
58
-
59
- // Get image links from HTML, to embed into the pdf
60
- let imgs = [];
61
- const srcs = $('img').map(function (i) {
62
- return $(this).attr('src');
63
- }).get();
64
- imgs.push(...srcs);
65
- for (let i = 0; i < imgs.length; i++) {
66
- if (!hdoc.valid_url(imgs[i])) {
67
- // Internal link
68
- const image_path = path.join(book_work_root, imgs[i].replace('_books/', ''));
69
- try {
70
- const image_buffer = fs.readFileSync(image_path);
71
- const mime_type = mime.lookup(image_path);
72
- let image_b64 = image_buffer.toString("base64");
73
- image_b64 = `data:${mime_type};base64,${image_b64}`;
74
- html_source = html_source.replace(imgs[i], image_b64);
75
- } catch (err) {
76
- console.log('Error reading image from HTML source [', image_path, '] -', err);
77
- return null;
78
- }
79
- } else {
80
- // External Link
81
- try {
82
- const file_response = await axios.get(imgs[i]);
83
- if (file_response.status === 200) {
84
- const image_buffer = file_response.data;
85
- const mime_type = mime.lookup(imgs[i]);
86
- let image_b64 = image_buffer.toString("base64");
87
- image_b64 = `data:${mime_type};base64,${image_b64}`;
88
- html_source = html_source.replace(imgs[i], image_b64);
89
- } else {
90
- throw `Unexpected Status ${file_response.status}`;
91
- }
92
- } catch (err) {
93
- console.log(`Error downloading external source [${imgs[i]}] - ${err}`);
94
- }
95
- }
96
- }
97
-
98
- return html_source;
99
- };
100
-
101
- exports.generate_pdf = async function (browser, pdf_template_path, pdf_template_content, book_config, html_source, target_file, css_templates, verbose = false) {
102
- let pdf_size = 0;
103
-
104
- // Cache footer
105
- if (footer === '') footer = get_footer(pdf_template_path);
106
-
107
- // Read svg logo file into buffer, convert to B64 string
108
- if (hb_logo === '') {
109
- const hb_logo_path = path.join(pdf_template_path, 'images', 'hornbill-logo-full.svg');
110
- try {
111
- const hb_logo_file_buffer = fs.readFileSync(hb_logo_path);
112
- hb_logo = hb_logo_file_buffer.toString("base64");
113
- hb_logo = `data:image/svg+xml;base64,${hb_logo}`;
114
- } catch (err) {
115
- console.log('Error reading logo from template:', err);
116
- return pdf_size;
117
- }
118
- }
119
-
120
- // Cache header
121
- if (header === '') {
122
- header = get_header(pdf_template_path).replace('{{book_title}}', book_config.title).replace('{{hb_logo}}', hb_logo);
123
- }
124
-
125
- html_source = pdf_template_content.replace('{{book_title}}', book_config.title).replace('{{document_content}}', html_source);
126
-
127
- const page = await browser.newPage();
128
-
129
- // To reflect CSS used for screens instead of print
130
- await page.emulateMediaType('screen');
131
-
132
- // Set HTML content from HTML source
133
- await page.setContent(html_source, {
134
- waitUntil: 'domcontentloaded'
135
- });
136
- for (let i = 0; i < css_templates.length; i++) {
137
- try {
138
- await page.addStyleTag({
139
- content: css_templates[i]
140
- });
141
- } catch (e) {
142
- console.log(`Error applying template for [${target_file}]: ${e}`);
143
- }
144
- }
145
-
146
- try {
147
- const pdf_gen = await page.pdf({
148
- path: target_file,
149
- printBackground: true,
150
- format: 'A4',
151
- displayHeaderFooter: true,
152
- headerTemplate: header,
153
- footerTemplate: footer,
154
- margin: {
155
- top: "90px",
156
- right: "30px",
157
- bottom: "60px",
158
- left: "30px"
159
- },
160
- timeout: 0
161
- });
162
- let currdate = new Date;
163
- let datetime = currdate.toISOString();
164
- if (verbose) console.log(`[${datetime}] PDF generation success: ${target_file}`);
165
-
166
- pdf_size = pdf_gen.byteLength;
167
- } catch (err) {
168
- console.log(`Error generating PDF ${target_file} - ${err}`);
169
- }
170
- await page.close();
171
- return pdf_size;
172
- };
1
+ (function () {
2
+ 'use strict';
3
+
4
+ const axios = require('axios'),
5
+ cheerio = require('cheerio'),
6
+ fs = require('fs-extra'),
7
+ mime = require('mime-types'),
8
+ path = require('path'),
9
+ hdoc = require(path.join(__dirname, 'hdoc-module.js'));
10
+
11
+ let hb_logo = '',
12
+ footer = '',
13
+ header = '';
14
+
15
+ const get_footer = function (template_path) {
16
+ let footer_content = null;
17
+ try {
18
+ footer_content = fs.readFileSync(path.join(template_path, 'template-footer.html'), 'utf8');
19
+ } catch (err) {
20
+ console.log(`Error loading template: ${err}`);
21
+ }
22
+ return footer_content;
23
+ };
24
+
25
+ const get_header = function (template_path) {
26
+ let header_content = null;
27
+ try {
28
+ header_content = fs.readFileSync(path.join(template_path, 'template-header.html'), 'utf8');
29
+ } catch (err) {
30
+ console.log(`Error loading template: ${err}`);
31
+ }
32
+ return header_content;
33
+ };
34
+
35
+ exports.process_images = async function (file_path, html_source, verbose) {
36
+ const book_work_root = file_path.path.replace(file_path.relativePath, '');
37
+ if (verbose) console.log('Parsing img tags from HTML source');
38
+
39
+ // Use cheerio to parse html
40
+ const $ = cheerio.load(html_source);
41
+
42
+ // Get iFrames from HTML, to replace with a tags
43
+ let iframes = [];
44
+ const iframe_html = $('iframe').map(function () {
45
+ const response = {
46
+ html: $.html(this),
47
+ src: $(this).attr('src'),
48
+ title: $(this).attr('title') ? $(this).attr('title') : 'No Link Title Provided'
49
+ };
50
+ return response;
51
+ }).get();
52
+ iframes.push(...iframe_html);
53
+ for (let i = 0; i < iframes.length; i++) {
54
+ const link = `<p><a href="${iframes[i].src}">${iframes[i].title}</a></p>`;
55
+ const regex = new RegExp(`<iframe.*src="${iframes[i].src.replace('/', '\\/')}".*</iframe>`);
56
+ html_source = html_source.replace(regex, link);
57
+ }
58
+
59
+ // Get image links from HTML, to embed into the pdf
60
+ let imgs = [];
61
+ const srcs = $('img').map(function (i) {
62
+ return $(this).attr('src');
63
+ }).get();
64
+ imgs.push(...srcs);
65
+ for (let i = 0; i < imgs.length; i++) {
66
+ if (!hdoc.valid_url(imgs[i])) {
67
+ // Internal link
68
+ const image_path = path.join(book_work_root, imgs[i].replace('_books/', ''));
69
+ try {
70
+ const image_buffer = fs.readFileSync(image_path);
71
+ const mime_type = mime.lookup(image_path);
72
+ let image_b64 = image_buffer.toString("base64");
73
+ image_b64 = `data:${mime_type};base64,${image_b64}`;
74
+ html_source = html_source.replace(imgs[i], image_b64);
75
+ } catch (err) {
76
+ console.log('Error reading image from HTML source [', image_path, '] -', err);
77
+ return null;
78
+ }
79
+ } else {
80
+ // External Link
81
+ try {
82
+ const file_response = await axios.get(imgs[i]);
83
+ if (file_response.status === 200) {
84
+ const image_buffer = file_response.data;
85
+ const mime_type = mime.lookup(imgs[i]);
86
+ let image_b64 = image_buffer.toString("base64");
87
+ image_b64 = `data:${mime_type};base64,${image_b64}`;
88
+ html_source = html_source.replace(imgs[i], image_b64);
89
+ } else {
90
+ throw `Unexpected Status ${file_response.status}`;
91
+ }
92
+ } catch (err) {
93
+ console.log(`Error downloading external source [${imgs[i]}] - ${err}`);
94
+ }
95
+ }
96
+ }
97
+
98
+ return html_source;
99
+ };
100
+
101
+ exports.generate_pdf = async function (browser, pdf_template_path, pdf_template_content, book_config, html_source, target_file, css_templates, verbose = false) {
102
+ let pdf_size = 0;
103
+
104
+ // Cache footer
105
+ if (footer === '') footer = get_footer(pdf_template_path);
106
+
107
+ // Read svg logo file into buffer, convert to B64 string
108
+ if (hb_logo === '') {
109
+ const hb_logo_path = path.join(pdf_template_path, 'images', 'hornbill-logo-full.svg');
110
+ try {
111
+ const hb_logo_file_buffer = fs.readFileSync(hb_logo_path);
112
+ hb_logo = hb_logo_file_buffer.toString("base64");
113
+ hb_logo = `data:image/svg+xml;base64,${hb_logo}`;
114
+ } catch (err) {
115
+ console.log('Error reading logo from template:', err);
116
+ return pdf_size;
117
+ }
118
+ }
119
+
120
+ // Cache header
121
+ if (header === '') {
122
+ header = get_header(pdf_template_path).replace('{{book_title}}', book_config.title).replace('{{hb_logo}}', hb_logo);
123
+ }
124
+
125
+ html_source = pdf_template_content.replace('{{book_title}}', book_config.title).replace('{{document_content}}', html_source);
126
+
127
+ const page = await browser.newPage();
128
+
129
+ // To reflect CSS used for screens instead of print
130
+ await page.emulateMediaType('screen');
131
+
132
+ // Set HTML content from HTML source
133
+ await page.setContent(html_source, {
134
+ waitUntil: 'domcontentloaded'
135
+ });
136
+ for (let i = 0; i < css_templates.length; i++) {
137
+ try {
138
+ await page.addStyleTag({
139
+ content: css_templates[i]
140
+ });
141
+ } catch (e) {
142
+ console.log(`Error applying template for [${target_file}]: ${e}`);
143
+ }
144
+ }
145
+
146
+ try {
147
+ const pdf_gen = await page.pdf({
148
+ path: target_file,
149
+ printBackground: true,
150
+ format: 'A4',
151
+ displayHeaderFooter: true,
152
+ headerTemplate: header,
153
+ footerTemplate: footer,
154
+ margin: {
155
+ top: "90px",
156
+ right: "30px",
157
+ bottom: "60px",
158
+ left: "30px"
159
+ },
160
+ timeout: 0
161
+ });
162
+ let currdate = new Date;
163
+ let datetime = currdate.toISOString();
164
+ if (verbose) console.log(`[${datetime}] PDF generation success: ${target_file}`);
165
+
166
+ pdf_size = pdf_gen.byteLength;
167
+ } catch (err) {
168
+ console.log(`Error generating PDF ${target_file} - ${err}`);
169
+ }
170
+ await page.close();
171
+ return pdf_size;
172
+ };
173
173
  })();
package/hdoc-create.js CHANGED
@@ -1,91 +1,91 @@
1
- (function () {
2
- 'use strict';
3
-
4
- const fs = require('fs-extra'),
5
- path = require('path'),
6
- hdoc = require(path.join(__dirname, 'hdoc-module.js'));
7
-
8
- let doc_id,
9
- processed_links = {},
10
- file_count = 0,
11
- folder_count = 0;
12
-
13
- exports.run = async function (source_path) {
14
-
15
- console.log('Hornbill HDocBook Create', '\n');
16
- console.log('Path:', source_path, '\n');
17
-
18
- // Load the hdocbook-project.json file to get the docId
19
- // use the docId to get the book config
20
- const hdocbook_project_config_path = path.join(source_path, 'hdocbook-project.json');
21
- let hdocbook_project = {};
22
- try {
23
- hdocbook_project = require(hdocbook_project_config_path);
24
- } catch (e) {
25
- console.log(`File not found: ${hdocbook_project_config_path}\n`);
26
- console.log('hdoc create needs to be run in the root of a HDoc Book.\n');
27
- process.exit(1);
28
- }
29
- doc_id = hdocbook_project.docId;
30
-
31
- const book_path = path.join(source_path, doc_id),
32
- hdocbook_path = path.join(book_path, 'hdocbook.json');
33
-
34
- let hdocbook = {};
35
- try {
36
- hdocbook = require(hdocbook_path);
37
- } catch (e) {
38
- console.log(`File not found: ${hdocbook_path}\n`);
39
- console.log('hdoc create needs to be run in the root of a HDoc Book.\n');
40
- process.exit(1);
41
- }
42
-
43
- // Get paths from breadcrumb builder
44
- let nav_paths = hdoc.build_breadcrumbs(hdocbook.navigation.items);
45
- for (const key in nav_paths) {
46
- if (nav_paths.hasOwnProperty(key)) {
47
- for (let i = 0; i < nav_paths[key].length; i++) {
48
- if (!processed_links[nav_paths[key][i].link]) {
49
- nav_paths[key][i].path = path.join(source_path, nav_paths[key][i].link);
50
- await add_doc(nav_paths[key][i]);
51
- }
52
- }
53
- }
54
- }
55
- console.log('\n-----------------------');
56
- console.log(' Docs Creation Summary');
57
- console.log('-----------------------\n');
58
- console.log(` Files Created: ${file_count}`);
59
- console.log(`Folders Created: ${folder_count}\n`);
60
- };
61
-
62
- const add_doc = async function(doc_info) {
63
-
64
- // Does folder exist? Create if not
65
- const folder = path.dirname(doc_info.path);
66
- if (!fs.existsSync(folder)) {
67
- try {
68
- fs.mkdirSync(folder, true);
69
- console.log('Folder created:', folder);
70
- folder_count++;
71
- } catch {
72
- console.log('\nError creating folder', folder, ':', e);
73
- return;
74
- }
75
- }
76
-
77
- // Does file exist? Create if not
78
- if (!fs.existsSync(doc_info.path + '.md') && !fs.existsSync(doc_info.path + '.htm') && !fs.existsSync(doc_info.path + '.html')) {
79
- try {
80
- const file_path = doc_info.path + '.md';
81
- fs.writeFileSync(file_path, `# ${doc_info.text}\n`);
82
- console.log(' File created:', file_path);
83
- processed_links[doc_info.link] = true;
84
- file_count++;
85
- } catch (e) {
86
- console.log('\nError creating file', doc_info.path, ':', e);
87
- }
88
- }
89
- }
90
-
1
+ (function () {
2
+ 'use strict';
3
+
4
+ const fs = require('fs-extra'),
5
+ path = require('path'),
6
+ hdoc = require(path.join(__dirname, 'hdoc-module.js'));
7
+
8
+ let doc_id,
9
+ processed_links = {},
10
+ file_count = 0,
11
+ folder_count = 0;
12
+
13
+ exports.run = async function (source_path) {
14
+
15
+ console.log('Hornbill HDocBook Create', '\n');
16
+ console.log('Path:', source_path, '\n');
17
+
18
+ // Load the hdocbook-project.json file to get the docId
19
+ // use the docId to get the book config
20
+ const hdocbook_project_config_path = path.join(source_path, 'hdocbook-project.json');
21
+ let hdocbook_project = {};
22
+ try {
23
+ hdocbook_project = require(hdocbook_project_config_path);
24
+ } catch (e) {
25
+ console.log(`File not found: ${hdocbook_project_config_path}\n`);
26
+ console.log('hdoc create needs to be run in the root of a HDoc Book.\n');
27
+ process.exit(1);
28
+ }
29
+ doc_id = hdocbook_project.docId;
30
+
31
+ const book_path = path.join(source_path, doc_id),
32
+ hdocbook_path = path.join(book_path, 'hdocbook.json');
33
+
34
+ let hdocbook = {};
35
+ try {
36
+ hdocbook = require(hdocbook_path);
37
+ } catch (e) {
38
+ console.log(`File not found: ${hdocbook_path}\n`);
39
+ console.log('hdoc create needs to be run in the root of a HDoc Book.\n');
40
+ process.exit(1);
41
+ }
42
+
43
+ // Get paths from breadcrumb builder
44
+ let nav_paths = hdoc.build_breadcrumbs(hdocbook.navigation.items);
45
+ for (const key in nav_paths) {
46
+ if (nav_paths.hasOwnProperty(key)) {
47
+ for (let i = 0; i < nav_paths[key].length; i++) {
48
+ if (!processed_links[nav_paths[key][i].link]) {
49
+ nav_paths[key][i].path = path.join(source_path, nav_paths[key][i].link);
50
+ await add_doc(nav_paths[key][i]);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ console.log('\n-----------------------');
56
+ console.log(' Docs Creation Summary');
57
+ console.log('-----------------------\n');
58
+ console.log(` Files Created: ${file_count}`);
59
+ console.log(`Folders Created: ${folder_count}\n`);
60
+ };
61
+
62
+ const add_doc = async function(doc_info) {
63
+
64
+ // Does folder exist? Create if not
65
+ const folder = path.dirname(doc_info.path);
66
+ if (!fs.existsSync(folder)) {
67
+ try {
68
+ fs.mkdirSync(folder, true);
69
+ console.log('Folder created:', folder);
70
+ folder_count++;
71
+ } catch {
72
+ console.log('\nError creating folder', folder, ':', e);
73
+ return;
74
+ }
75
+ }
76
+
77
+ // Does file exist? Create if not
78
+ if (!fs.existsSync(doc_info.path + '.md') && !fs.existsSync(doc_info.path + '.htm') && !fs.existsSync(doc_info.path + '.html')) {
79
+ try {
80
+ const file_path = doc_info.path + '.md';
81
+ fs.writeFileSync(file_path, `# ${doc_info.text}\n`);
82
+ console.log(' File created:', file_path);
83
+ processed_links[doc_info.link] = true;
84
+ file_count++;
85
+ } catch (e) {
86
+ console.log('\nError creating file', doc_info.path, ':', e);
87
+ }
88
+ }
89
+ }
90
+
91
91
  })();