view client/src/components/Pdftool.vue @ 1874:bad32adafef2 dev-pdf-generation

client: add real pdf generation with jspdf * Add jspdf dependency. * Change Pdftool to not deliver the fixed pdfs, but to try to generate a plain pdf. This has just the map for now and only works, if the external servers rightfully send a well formed 'Access-Control-Allow-Origin' header.
author Bernhard Reiter <bernhard@intevation.de>
date Thu, 20 Dec 2018 15:06:38 +0100
parents ca48145dba9c
children e53924abb4a2
line wrap: on
line source

<template>
  <div
    :class="[
      'box ui-element rounded bg-white text-nowrap',
      { expanded: showPdfTool }
    ]"
  >
    <div style="width: 20rem">
      <h6 class="mb-0 py-2 px-3 border-bottom d-flex align-items-center">
        <font-awesome-icon icon="file-pdf" class="mr-2"></font-awesome-icon
        ><translate>Generate PDF</translate>
        <font-awesome-icon
          icon="times"
          class="ml-auto text-muted"
          @click="$store.commit('application/showPdfTool', false)"
        ></font-awesome-icon>
      </h6>
      <div class="p-3">
        <b><translate>Chose format:</translate></b>
        <select v-model="form.format" class="form-control d-block w-100">
          <option value="landscape"><translate>landscape</translate></option>
          <option value="portrait"><translate>portrait</translate></option>
        </select>
        <select v-model="form.paperSize" class="form-control d-block w-100">
          <option value="a3"><translate>ISO A3</translate></option>
          <option value="a4"><translate>ISO A4</translate></option>
        </select>
        <small class="d-block my-2">
          <input
            type="radio"
            id="pdfexport-downloadtype-download"
            value="download"
            v-model="form.downloadType"
            selected
          />
          <label for="pdfexport-downloadtype-download" class="ml-1 mr-2"
            ><translate>Download</translate></label
          >
          <input
            type="radio"
            id="pdfexport-downloadtype-open"
            value="open"
            v-model="form.downloadType"
          />
          <label for="pdfexport-downloadtype-open" class="ml-1"
            ><translate>Open in new window</translate></label
          >
        </small>
        <button
          @click="download"
          type="button"
          class="btn btn-sm btn-info d-block w-100"
        >
          <translate>Generate PDF</translate>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
/* This is Free Software under GNU Affero General Public License v >= 3.0
 * without warranty, see README.md and license for details.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 * License-Filename: LICENSES/AGPL-3.0.txt
 *
 * Copyright (C) 2018 by via donau
 *   – Österreichische Wasserstraßen-Gesellschaft mbH
 * Software engineering by Intevation GmbH
 *
 * Author(s):
 * * Markus Kottländer <markus.kottlaender@intevation.de>
 * * Bernhard E. Reiter <bernhard@intevation.de>
 */
import { mapState } from "vuex";
import jsPDF from "jspdf";

var paperSizes = {
  // in millimeter, landscape [width, height]
  a3: [420, 297],
  a4: [297, 210]
};

export default {
  name: "pdftool",
  data() {
    return {
      form: {
        format: "landscape",
        paperSize: "a4",
        downloadType: "download"
      }
    };
  },
  computed: {
    ...mapState("map", ["openLayersMap"]),
    ...mapState("application", ["showPdfTool"]),
    ...mapState("bottlenecks", ["selectedSurvey"])
  },
  methods: {
    download() {
      // FUTURE: disable button while working on it
      console.log(
        "will generate pdf with",
        this.form.paperSize,
        this.form.format
      );

      var width, height;
      // generate PDF and open it
      if (this.form.format !== "portrait") {
        // landscape, default
        width = paperSizes[this.form.paperSize][0];
        height = paperSizes[this.form.paperSize][1];
      } else {
        // switch width and height
        width = paperSizes[this.form.paperSize][1];
        height = paperSizes[this.form.paperSize][0];
      }

      let resolution = 120; // Dots per inch. An inch is 25.4 mm.

      // FUTURE: consider margins
      console.log(width, height);

      var map = this.openLayersMap;
      var mapSize = map.getSize(); // size in pixels of the map in the DOM

      // Calculate the extent for the current view state and the passed size.
      // The size is the pixel dimensions of the box into which the calculated
      // extent should fit.
      var mapExtent = map.getView().calculateExtent(mapSize);

      var pdf = new jsPDF(this.form.format, "mm", this.form.paperSize);

      // set a callback for after the next complete rendering of the map
      map.once("rendercomplete", function(event) {
        let canvas = event.context.canvas;
        console.log("rendered", canvas);
        var data = canvas.toDataURL("image/png");
        pdf.addImage(data, "PNG", 0, 0, width, height);

        pdf.save("map.pdf");

        // reset to original size
        map.setSize(mapSize);
        map.getView().fit(mapExtent, { size: mapSize });

        // FUTURE: re-enable button when done
      });

      // trigger rendering
      var mapSizeForPrint = [
        Math.round((width * resolution) / 25.4),
        Math.round((height * resolution) / 25.4)
      ];
      map.setSize(mapSizeForPrint);
      map.getView().fit(mapExtent, { size: mapSizeForPrint });

      // TODO: replace this src with an API reponse after actually generating PDFs
      /*
      let src =
        this.form.format === "landscape"
          ? "/img/PrintTemplate-Var2-Landscape.pdf"
          : "/img/PrintTemplate-Var2-Portrait.pdf";

      let a = document.createElement("a");
      a.href = src;

      if (this.form.downloadType === "download")
        a.download = src.substr(src.lastIndexOf("/") + 1);
      else a.target = "_blank";

      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      */
    }
  }
};
</script>