chromiumly 1.0.0

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.
@@ -0,0 +1,17 @@
1
+ name: Publish
2
+ on:
3
+ release:
4
+ types: [published]
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - uses: actions/setup-node@v2
11
+ with:
12
+ node-version: '14.x'
13
+ registry-url: 'https://registry.npmjs.org'
14
+ - run: yarn
15
+ - run: yarn publish --access public
16
+ env:
17
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Taha Abdelmoutaleb Cherfia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # Chromiumly
2
+
3
+ A lightweight Typescrpit library which interacts with [Gotenberg](https://gotenberg.dev/)'s Chromium module to convert HTML documents to PDF.
4
+
5
+ ## Prerequisites
6
+
7
+ Before attempting to use Chromiumly, be sure you install [Docker](https://www.docker.com/) if you have not already done so.
8
+
9
+ After that, you can start a default Docker container of [Gotenberg](https://gotenberg.dev/) as follows:
10
+
11
+ ```bash
12
+ docker run --rm -p 3000:3000 gotenberg/gotenberg:7
13
+ ```
14
+
15
+ ## Get Started
16
+
17
+ ### Configuration
18
+
19
+ Chromiumly supports both [dotenv](https://www.npmjs.com/package/dotenv) and [config](https://www.npmjs.com/package/config) configuration libraries to add Gotenberg endpoint to your project.
20
+
21
+ #### dotenv
22
+
23
+ ```bash
24
+ GOTENBERG_ENDPOINT=localhost:3000
25
+ ```
26
+
27
+ #### config
28
+
29
+ ```json
30
+ {
31
+ "gotenberg": {
32
+ "enpdoint": "localhost:3000"
33
+ }
34
+ }
35
+ ```
36
+
37
+ ### Usage
38
+
39
+ Chromiumly introduces different classes that serve as wrappers to Gotenberg's Chromium [routes](https://gotenberg.dev/docs/modules/chromium#routes).
40
+
41
+ Each class comes with two methods :
42
+
43
+ #### convert
44
+
45
+ This method takes either a `url`, an `html` file path or `html` and `markdown` file paths and returns a `buffer` which contains the converted PDF file content.
46
+
47
+ #### generate
48
+
49
+ It is just a generic complementary method that takes the `buffer` returned by the `convert` method, and a chosen `filename` to generate the PDF file.
50
+
51
+ Please note that all the PDF files can be found `__generated__` folder in the root folder of your project
52
+
53
+ ### Modules
54
+
55
+ #### URL
56
+
57
+ ```typescript
58
+ import { UrlConverter } from "chromiumly";
59
+
60
+ const urlConverter = new UrlConverter();
61
+ const buffer = await urlConverter.convert({
62
+ url: "https://www.example.com/",
63
+ });
64
+ ```
65
+
66
+ #### HTML
67
+
68
+ The only requirement is that the file name should be `index.html`.
69
+
70
+ ```typescript
71
+ import { HtmlConverter } from "chromiumly";
72
+
73
+ const htmlConverter = new HtmlConverter();
74
+ const buffer = await htmlConverter.convert({
75
+ html: "path/to/index.html",
76
+ });
77
+
78
+ ```
79
+
80
+ #### Markdown
81
+
82
+ This route accepts an `index.html` file plus a markdown file.
83
+
84
+ ```typescript
85
+ import { MarkdownConverter } from "chromiumly";
86
+
87
+ const markdownConverter = new MarkdownConverter();
88
+ const buffer = await markdownConverter.convert({
89
+ html: "path/to/index.html",
90
+ markdown: "path/to/file.md",
91
+ });
92
+ ```
93
+
94
+ ### Customization
95
+
96
+ `convert()` method takes an optional `properties` parameter of the following type which dictates how the PDF generated file will look like.
97
+
98
+ ```typescript
99
+ type PageProperties = {
100
+ size?: {
101
+ width: number; // Paper width, in inches (default 8.5)
102
+ height: number; //Paper height, in inches (default 11)
103
+ };
104
+ margins?: {
105
+ top: number; // Top margin, in inches (default 0.39)
106
+ bottom: number; // Bottom margin, in inches (default 0.39)
107
+ left: number; // Left margin, in inches (default 0.39)
108
+ right: number; // Right margin, in inches (default 0.39)
109
+ };
110
+ preferCssPageSize?: boolean; // Define whether to prefer page size as defined by CSS (default false)
111
+ printBackground?: boolean; // Print the background graphics (default false)
112
+ landscape?: boolean; // Set the paper orientation to landscape (default false)
113
+ scale?: number; // The scale of the page rendering (default 1.0)
114
+ nativePageRanges?: { from: number; to: number }; // Page ranges to print
115
+ };
116
+ ```
117
+
118
+ ### Snippet
119
+
120
+ The following is a short snippet of how to use the library.
121
+
122
+ ```typescript
123
+ import { UrlConverter } from "chromiumly";
124
+
125
+ async function run() {
126
+ const urlConverter = new UrlConverter();
127
+ const buffer = await urlConverter.convert({
128
+ url: "https://gotenberg.dev/",
129
+ });
130
+
131
+ await urlConverter.generate("gotenberg.pdf", buffer);
132
+ }
133
+
134
+ run();
135
+ ```
package/dist/main.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UrlConverter = exports.MarkdownConverter = exports.HtmlConverter = void 0;
4
+ var html_converter_1 = require("./converters/html.converter");
5
+ Object.defineProperty(exports, "HtmlConverter", { enumerable: true, get: function () { return html_converter_1.HtmlConverter; } });
6
+ var markdown_converter_1 = require("./converters/markdown.converter");
7
+ Object.defineProperty(exports, "MarkdownConverter", { enumerable: true, get: function () { return markdown_converter_1.MarkdownConverter; } });
8
+ var url_converter_1 = require("./converters/url.converter");
9
+ Object.defineProperty(exports, "UrlConverter", { enumerable: true, get: function () { return url_converter_1.UrlConverter; } });
10
+ //# sourceMappingURL=main.js.map
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "chromiumly",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight Typescrpit library which interacts with Gotenberg's Chromium module to convert HTML documents to PDF.",
5
+ "main": "dist/main.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/cherfia/chromiumly.git"
9
+ },
10
+ "author": "Taha Cherfia <taha.cherfia@gmail.com>",
11
+ "license": "MIT",
12
+ "engines": {
13
+ "node": "14.x"
14
+ },
15
+ "scripts": {
16
+ "clean": "rm -rf dist build",
17
+ "lint": "eslint src/ --ext .js,.ts",
18
+ "build": "yarn clean && tsc -p tsconfig.json"
19
+ },
20
+ "devDependencies": {
21
+ "@types/config": "^0.0.41",
22
+ "@types/dotenv": "^8.2.0",
23
+ "@types/form-data": "^2.5.0",
24
+ "@types/node": "^17.0.22",
25
+ "@types/node-fetch": "2",
26
+ "@typescript-eslint/eslint-plugin": "^5.16.0",
27
+ "@typescript-eslint/parser": "^5.16.0",
28
+ "eslint": "^8.11.0",
29
+ "ts-node": "^10.7.0",
30
+ "typescript": "^4.6.2"
31
+ },
32
+ "dependencies": {
33
+ "config": "^3.3.7",
34
+ "dotenv": "^16.0.0",
35
+ "form-data": "^4.0.0",
36
+ "node-fetch": "2"
37
+ }
38
+ }
@@ -0,0 +1,11 @@
1
+ import { PathLike } from "fs";
2
+
3
+ import { PageProperties } from "./converter.types";
4
+
5
+ export interface IConverter {
6
+ convert({
7
+ ...args
8
+ }: {
9
+ [x: string]: string | PathLike | PageProperties;
10
+ }): Promise<Buffer>;
11
+ }
@@ -0,0 +1,18 @@
1
+ import { promises } from "fs";
2
+ import path from "path";
3
+
4
+ import { Chromiumly, Route } from "../main.config";
5
+
6
+ export abstract class Converter {
7
+ readonly endpoint: string;
8
+
9
+ constructor(route: Route) {
10
+ this.endpoint = `${Chromiumly.endpoint}/${Chromiumly.path}/${Chromiumly.routes[route]}`;
11
+ }
12
+
13
+ async generate(filename: string, buffer: Buffer): Promise<void> {
14
+ const __generated__ = path.resolve(process.cwd(), "__generated__");
15
+ await promises.mkdir(path.resolve(__generated__), { recursive: true });
16
+ await promises.writeFile(path.resolve(__generated__, filename), buffer);
17
+ }
18
+ }
@@ -0,0 +1,21 @@
1
+ type PageSize = {
2
+ width: number; // Paper width, in inches (default 8.5)
3
+ height: number; //Paper height, in inches (default 11)
4
+ };
5
+
6
+ type PageMargins = {
7
+ top: number; // Top margin, in inches (default 0.39)
8
+ bottom: number; // Bottom margin, in inches (default 0.39)
9
+ left: number; // Left margin, in inches (default 0.39)
10
+ right: number; // Right margin, in inches (default 0.39)
11
+ };
12
+
13
+ export type PageProperties = {
14
+ size?: PageSize;
15
+ margins?: PageMargins;
16
+ preferCssPageSize?: boolean; // Define whether to prefer page size as defined by CSS (default false)
17
+ printBackground?: boolean; // Print the background graphics (default false)
18
+ landscape?: boolean; // Set the paper orientation to landscape (default false)
19
+ scale?: number; // The scale of the page rendering (default 1.0)
20
+ nativePageRanges?: { from: number; to: number }; // Page ranges to print
21
+ };
@@ -0,0 +1,101 @@
1
+ import FormData from "form-data";
2
+ import fetch from "node-fetch";
3
+
4
+ import { PageProperties } from "./converter.types";
5
+
6
+ export class ConverterUtils {
7
+ private static assert(
8
+ condition: boolean,
9
+ message: string
10
+ ): asserts condition {
11
+ if (!condition) {
12
+ throw new Error(message);
13
+ }
14
+ }
15
+
16
+ public static injectPageProperties(
17
+ data: FormData,
18
+ pageProperties: PageProperties
19
+ ): void {
20
+ if (pageProperties) {
21
+ if (pageProperties.size) {
22
+ ConverterUtils.assert(
23
+ pageProperties.size.width >= 1.0 && pageProperties.size.height >= 1.5,
24
+ "size is smaller than the minimum printing requirements (i.e. 1.0 x 1.5 in)"
25
+ );
26
+
27
+ data.append("paperWidth", pageProperties.size.width);
28
+ data.append("paperHeight", pageProperties.size.height);
29
+ }
30
+
31
+ if (pageProperties.margins) {
32
+ ConverterUtils.assert(
33
+ pageProperties.margins.top >= 0 &&
34
+ pageProperties.margins.bottom >= 0 &&
35
+ pageProperties.margins.left >= 0 &&
36
+ pageProperties.margins.left >= 0,
37
+ "negative margins are not allowed"
38
+ );
39
+
40
+ data.append("marginTop", pageProperties.margins.top);
41
+ data.append("marginBottom", pageProperties.margins.bottom);
42
+ data.append("marginLeft", pageProperties.margins.left);
43
+ data.append("marginRight", pageProperties.margins.right);
44
+ }
45
+
46
+ if (pageProperties.preferCssPageSize) {
47
+ data.append(
48
+ "preferCssPageSize",
49
+ String(pageProperties.preferCssPageSize)
50
+ );
51
+ }
52
+
53
+ if (pageProperties.printBackground) {
54
+ data.append("printBackground", String(pageProperties.printBackground));
55
+ }
56
+
57
+ if (pageProperties.landscape) {
58
+ data.append("landscape", String(pageProperties.landscape));
59
+ }
60
+
61
+ if (pageProperties.scale) {
62
+ ConverterUtils.assert(
63
+ pageProperties.scale >= 0.1 && pageProperties.scale <= 2.0,
64
+ "scale is outside of [0.1 - 2] range"
65
+ );
66
+
67
+ data.append("scale", pageProperties.scale);
68
+ }
69
+
70
+ if (pageProperties.nativePageRanges) {
71
+ ConverterUtils.assert(
72
+ pageProperties.nativePageRanges.from > 0 &&
73
+ pageProperties.nativePageRanges.to > 0 &&
74
+ pageProperties.nativePageRanges.to >=
75
+ pageProperties.nativePageRanges.from,
76
+ "page ranges syntax error"
77
+ );
78
+
79
+ data.append(
80
+ "nativePageRanges",
81
+ `${pageProperties.nativePageRanges.from}-${pageProperties.nativePageRanges.to}`
82
+ );
83
+ }
84
+ }
85
+ }
86
+
87
+ static async fetch(endpoint: string, data: FormData): Promise<Buffer> {
88
+ const response = await fetch(endpoint, {
89
+ method: "post",
90
+ body: data,
91
+ headers: {
92
+ ...data.getHeaders(),
93
+ },
94
+ });
95
+
96
+ if (!response.ok) {
97
+ throw new Error(`${response.status} ${response.statusText}`);
98
+ }
99
+ return response.buffer();
100
+ }
101
+ }
@@ -0,0 +1,30 @@
1
+ import { createReadStream, PathLike } from "fs";
2
+
3
+ import FormData from "form-data";
4
+
5
+ import { IConverter } from "../common/converter.interface";
6
+ import { PageProperties } from "../common/converter.types";
7
+ import { ConverterUtils } from "../common/converter.utils";
8
+ import { Converter } from "../common/converter";
9
+ import { Route } from "../main.config";
10
+
11
+ export class HtmlConverter extends Converter implements IConverter {
12
+ constructor() {
13
+ super(Route.HTML);
14
+ }
15
+
16
+ async convert({
17
+ html,
18
+ properties,
19
+ }: {
20
+ html: PathLike;
21
+ properties?: PageProperties;
22
+ }): Promise<Buffer> {
23
+ const data = new FormData();
24
+ data.append("index.html", createReadStream(html));
25
+ if (properties) {
26
+ ConverterUtils.injectPageProperties(data, properties);
27
+ }
28
+ return ConverterUtils.fetch(this.endpoint, data);
29
+ }
30
+ }
@@ -0,0 +1,33 @@
1
+ import { createReadStream, PathLike } from "fs";
2
+
3
+ import FormData from "form-data";
4
+
5
+ import { IConverter } from "../common/converter.interface";
6
+ import { PageProperties } from "../common/converter.types";
7
+ import { ConverterUtils } from "../common/converter.utils";
8
+ import { Converter } from "../common/converter";
9
+ import { Route } from "../main.config";
10
+
11
+ export class MarkdownConverter extends Converter implements IConverter {
12
+ constructor() {
13
+ super(Route.MARKDOWN);
14
+ }
15
+
16
+ async convert({
17
+ html,
18
+ markdown,
19
+ properties,
20
+ }: {
21
+ html: PathLike;
22
+ markdown: PathLike;
23
+ properties?: PageProperties;
24
+ }): Promise<Buffer> {
25
+ const data = new FormData();
26
+ data.append("index.html", createReadStream(html));
27
+ data.append("file.md", createReadStream(markdown));
28
+ if (properties) {
29
+ ConverterUtils.injectPageProperties(data, properties);
30
+ }
31
+ return ConverterUtils.fetch(this.endpoint, data);
32
+ }
33
+ }
@@ -0,0 +1,35 @@
1
+ import { URL } from "url";
2
+
3
+ import FormData from "form-data";
4
+
5
+ import { IConverter } from "../common/converter.interface";
6
+ import { PageProperties } from "../common/converter.types";
7
+ import { ConverterUtils } from "../common/converter.utils";
8
+ import { Converter } from "../common/converter";
9
+ import { Route } from "../main.config";
10
+
11
+ export class UrlConverter extends Converter implements IConverter {
12
+ constructor() {
13
+ super(Route.URL);
14
+ }
15
+
16
+ async convert({
17
+ url,
18
+ properties,
19
+ }: {
20
+ url: string;
21
+ properties?: PageProperties;
22
+ }): Promise<Buffer> {
23
+ try {
24
+ const _url = new URL(url);
25
+ const data = new FormData();
26
+ data.append("url", _url.href);
27
+ if (properties) {
28
+ ConverterUtils.injectPageProperties(data, properties);
29
+ }
30
+ return ConverterUtils.fetch(this.endpoint, data);
31
+ } catch (error) {
32
+ throw error;
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,9 @@
1
+ process.env.SUPPRESS_NO_CONFIG_WARNING = "y";
2
+
3
+ import "dotenv/config";
4
+ import config from "config";
5
+
6
+ export class Gotenberg {
7
+ public static endpoint: string =
8
+ process.env.GOTENBERG_ENDPOINT || config.get<string>("gotenberg.endpoint");
9
+ }
@@ -0,0 +1,23 @@
1
+ import { Gotenberg } from "./gotenberg";
2
+
3
+ export enum Route {
4
+ URL = "url",
5
+ HTML = "html",
6
+ MARKDOWN = "markdown",
7
+ }
8
+
9
+ export class Chromiumly {
10
+ private static readonly GOTENBERG_ENDPOINT = Gotenberg.endpoint;
11
+
12
+ private static readonly PATH = "forms/chromium/convert";
13
+
14
+ private static readonly ROUTES = {
15
+ url: Route.URL,
16
+ html: Route.HTML,
17
+ markdown: Route.MARKDOWN,
18
+ };
19
+
20
+ public static readonly endpoint = Chromiumly.GOTENBERG_ENDPOINT;
21
+ public static readonly path = Chromiumly.PATH;
22
+ public static readonly routes = Chromiumly.ROUTES;
23
+ }
package/src/main.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { HtmlConverter } from "./converters/html.converter";
2
+ export { MarkdownConverter } from "./converters/markdown.converter";
3
+ export { UrlConverter } from "./converters/url.converter";
package/tsconfig.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6",
4
+ "module": "commonjs",
5
+ "moduleResolution": "node",
6
+ "declaration": true,
7
+ "strict": true,
8
+ "noImplicitAny": true,
9
+ "strictNullChecks": true,
10
+ "strictFunctionTypes": true,
11
+ "noUnusedLocals": true,
12
+ "noUnusedParameters": true,
13
+ "noImplicitReturns": true,
14
+ "noFallthroughCasesInSwitch": true,
15
+ "importHelpers": true,
16
+ "skipLibCheck": true,
17
+ "esModuleInterop": true,
18
+ "allowSyntheticDefaultImports": true,
19
+ "experimentalDecorators": true,
20
+ "sourceMap": true,
21
+ "outDir": "./dist",
22
+ "types": ["node"],
23
+ "lib": ["ES6"]
24
+ },
25
+ "include": ["src/**/*.ts"],
26
+ "exclude": ["node_modules", "**/*.test.ts"]
27
+ }