wkhtmltopdf.js 1.87 KiB
import { callbackify } from "util";
import { createReadStream } from "fs";
import exec from "./exec";
import logger from "gulplog";
import { mkTempFile } from "./tempdir";
import { obj } from "through2";
import path from "path";
import PluginError from "plugin-error";
import { withBinary } from "./optional";
const PLUGIN_NAME = "wkhtmltopdf";
const DEFAULT_OPTIONS = {
  args: [
    "--quiet",
    "--orientation",
    "Landscape",
    "--page-size",
    "A4",
    "--background",
    "--print-media-type",
    "--enable-local-file-access",
    "--margin-bottom",
    "0",
    "--margin-left",
    "0",
    "--margin-right",
    "0",
    "--margin-top",
    "0",
/**
 * @param {File} input
 * @return {string}
export function getPDFOutput(input) {
  const output = input.clone({ deep: false, contents: false });
  output.basename = path.basename(input.dirname, ".md") + ".pdf";
  return output;
export const wkhtmltopdf = withBinary(
  "WKHTMLTOPDF_BINARY",
  "wkhtmltopdf",
  (WKHTMLTOPDF_BINARY) =>
    function wkhtmltopdf(options = {}) {
      const { args } = Object.assign({}, DEFAULT_OPTIONS, options);
      return obj(
        callbackify(async function (input) {
          try {
            const output = await mkTempFile(getPDFOutput(input));
            const execArgs = [
              ...args,
              `file://${input.path}?print-pdf`,
              output.path,
            await exec(PLUGIN_NAME, WKHTMLTOPDF_BINARY, execArgs);
            logger.info(
              "%s: %s -> %s",
              PLUGIN_NAME,
              input.relative,
              output.relative
            output.contents = createReadStream(output.path);
            this.push(output);
          } catch (err) {
717273747576777879
throw new PluginError(PLUGIN_NAME, err, { filename: input.path }); } }) ); } ); export default wkhtmltopdf;