Export pdf

by Vladimir Vershinin

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v5.3.0/build/ol.js"></script>
<script src="https://unpkg.com/[email protected]/dist/fakerator.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/lib/style.css">
<div id="app">
  <div>
    <button @click="exportMap">Export</button>
    {{ message }}
  </div>

  <vl-map ref="map" :load-tiles-while-animating="true" :load-tiles-while-interacting="true" data-projection="EPSG:4326">
    <vl-view ref="mapView" :zoom.sync="zoom" :center.sync="center"></vl-view>

    <vl-layer-tile id="osm">
      <vl-source-osm></vl-source-osm>
    </vl-layer-tile>

    <vl-feature id="position-feature" ref="positionMarker" :properties="{ start: Date.now(), duration: 2500 }">
      <template slot-scope="feature">
        <vl-geom-polygon :coordinates="[[[0, 0], [20, 0], [20, 20], [0, 20], [0, 0]]]"></vl-geom-polygon>
      </template>
    </vl-feature>
  </vl-map>
</div>

CSS

html, body, #app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.layers {
  position: absolute;
  top: 10px;
  left: 50px;
  z-index: 1;
}

JavaScript

var dims = {
  a0: [1189, 841],
  a1: [841, 594],
  a2: [594, 420],
  a3: [420, 297],
  a4: [297, 210],
  a5: [210, 148]
};

new Vue({
  el: '#app',
  data() {
    return {
      zoom: 2,
      center: [0, 0],
      features: [],
      format: 'a4',
      resolution: 72,
      message: '',
    }
  },
  methods: {
    exportMap() {
      var map = this.$refs.map.$map;
      var dim = dims[this.format];
      var width = Math.round(dim[0] * this.resolution / 25.4);
      var height = Math.round(dim[1] * this.resolution / 25.4);
      var size = /** @type {module:ol/size~Size} */ (map.getSize());
      var extent = map.getView().calculateExtent(size);

      this.message = 'exporting...';

      map.once('rendercomplete', function(event) {
        var canvas = event.context.canvas;
        var data = canvas.toDataURL('image/jpeg');
        var pdf = new jsPDF('landscape', undefined, this.format);
        pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
        pdf.save('map.pdf');
        // Reset original map size
        map.setSize(size);
        map.getView().fit(extent, {
          size: size
        });

        this.message = '';
      });

      // Set print size
      var printSize = [width, height];
      map.setSize(printSize);
      map.getView().fit(extent, {
        size: printSize
      });
    },
  },
})