Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
printer.js 6.01 KiB
const Paged = require('pagedjs');
const EventEmitter = require('events');
const puppeteer = require('puppeteer');
const util = require('util');
const fs = require('fs');
const fetch = require("node-fetch");

const path = require('path');

let dir = process.cwd();

// Find top most pagedjs
let pagedjsLocation = require.resolve("pagedjs/dist/paged.polyfill.js");
let paths = pagedjsLocation.split("node_modules");
let scriptPath = paths[0] + "node_modules" + paths[paths.length-1];

const PostProcesser = require('./postprocesser');

const PDF_SETTINGS = {
  printBackground: true,
  displayHeaderFooter: false,
  preferCSSPageSize: true,
  margin: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
  }
};

class Printer extends EventEmitter {
  constructor(headless, allowLocal) {
    super();
    this.headless = headless !== false;
    this.allowLocal = allowLocal;
    this.pages = [];
  }

  async setup() {
    const browser = await puppeteer.launch({
      headless: this.headless,
      args: this.allowLocal ? ['--allow-file-access-from-files', '--disable-dev-shm-usage', '--no-sandbox'] : ['--disable-dev-shm-usage', '--no-sandbox'],
      ignoreHTTPSErrors: true
    });

    return browser;
  }

  async render(input) {
    let resolver;
    let rendered = new Promise(function(resolve, reject) {
      resolver = resolve;
    });

    if (!this.browser) {
      this.browser = await this.setup();
    }

    const page = await this.browser.newPage();

    let uri, url, html;
    if (typeof input === "string") {
      try {
        uri = new URL(input);
        if (uri.protocol === "https:") {
          html = await fetch(input)
            .then(res => res.text())
        }
        url = input;
      } catch {