api/page: printToPDF: provide margins option via object and fix

This commit is contained in:
CanadaHonk 2023-01-31 09:11:08 +00:00
parent 7f22aa55b0
commit 2d1c049a6d
2 changed files with 38 additions and 22 deletions

24
gluon.d.ts vendored
View File

@ -91,28 +91,34 @@ type PrintToPDFOptions = {
paperHeight?: number, paperHeight?: number,
/** /**
* Top margin in inches. * Set the margins of the PDF (inches).
* @default 0.4 * @default 0.4 for all
*/ */
marginTop?: number, margins?: {
/**
* Top margin in inches.
* @default 0.4 (1cm)
*/
top?: number,
/** /**
* Bottom margin in inches. * Bottom margin in inches.
* @default 0.4 * @default 0.4 (1cm)
*/ */
marginBottom?: number, bottom?: number,
/** /**
* Left margin in inches. * Left margin in inches.
* @default 0.4 * @default 0.4 (1cm)
*/ */
marginLeft?: number, left?: number,
/** /**
* Right margin in inches. * Right margin in inches.
* @default 0.4 * @default 0.4 (1cm)
*/ */
marginRight?: number, right?: number
},
/** /**
* Paper ranges to print, one based, (eg '1-5, 8, 11-13'). * Paper ranges to print, one based, (eg '1-5, 8, 11-13').

View File

@ -118,19 +118,29 @@ export default async (CDP, proc, injectionType = 'browser', { dataPath, browserN
}, },
printToPDF: async (...args) => { printToPDF: async (...args) => {
let path, options; let path, options = {};
if (args.length === 1) { if (args.length === 1) {
if (typeof args[0] === 'string') path = args[0]; if (typeof args[0] === 'string') path = args[0];
else options = args[0]; else options = { ...args[0] };
} }
if (args.length === 2) { if (args.length === 2) {
[ path, options ] = args; path = args[0];
options = { ...args[1] };
} }
if (options.margins) {
const { top, bottom, left, right } = options.margins;
if (top) options.marginTop = top;
if (bottom) options.marginBottom = bottom;
if (left) options.marginLeft = left;
if (right) options.marginRight = right;
const { data } = await CDP.send('Page.printToPDF', options); delete options.margins;
}
const { data } = await Window.cdp.send('Page.printToPDF', options);
const buffer = Buffer.from(data, 'base64'); const buffer = Buffer.from(data, 'base64');
if (path) await writeFile(path, buffer); if (path) await writeFile(path, buffer);