Printing in Openlayers 3 (pdf) - openlayers-3

I have made a printing tools for openlayers 3 which prints in PDF format. Here is my code to print in pdf.
var dims = {
a0: [1189, 841],
a1: [841, 594],
a2: [594, 420],
a3: [420, 297],
a4: [297, 210],
a5: [210, 148]
};
var exportElement = document.getElementById('export-pdf');
exportElement.addEventListener('click', function(e) {
if (exportElement.className.indexOf('disabled') > -1) {
return;
}
exportElement.className += ' disabled';
var format = document.getElementById('format').value;
var resolution = document.getElementById('resolution').value;
var buttonLabelElement = document.getElementById('button-label');
var label = buttonLabelElement.innerText;
var dim = dims[format];
var width = Math.round(dim[0] * resolution / 25.4);
var height = Math.round(dim[1] * resolution / 25.4);
var size = /** #type {ol.Size} */ (map.getSize());
var extent = map.getView().calculateExtent(size);
map.once('postcompose', function(event) {
//var tileQueue = map.getTileQueue();
// To prevent potential unexpected division-by-zero
// behaviour, tileTotalCount must be larger than 0.
//var tileTotalCount = tileQueue.getCount() || 1;
var interval;
interval = setInterval(function() {
//var tileCount = tileQueue.getCount();
//var ratio = 1 - tileCount / tileTotalCount;
//buttonLabelElement.innerText = ' ' + (100 * ratio).toFixed(1) + '%';
//if (ratio == 1 && !tileQueue.getTilesLoading()) {
clearInterval(interval);
buttonLabelElement.innerText = label;
var canvas = event.context.canvas;
var data = canvas.toDataURL('image/jpeg');
var pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
pdf.save('map.pdf');
map.setSize(size);
map.getView().fitExtent(extent, size);
map.renderSync();
exportElement.className =
exportElement.className.replace(' disabled', '');
// }
}, 100);
});
map.setSize([width, height]);
map.getView().fitExtent(extent, /** #type {ol.Size} */ (map.getSize()));
map.renderSync();
}, false);
I can print in PDF when I have only OSM Layer but when I add local layers from my geoserver I can't print anything and the whole application is freezed.
Can anyone tell me what am I doing wrong here?
I am using jspdf to print pdf.
AJ

Your problem is that you load imagery from other domains, and haven't configured them for CORS. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for a description on cross origin image use.
In order to get data out of the canvas, all images put into it must be from the same domain or transmitted with the appropriate Access-Control-Allow-Origin header.
I would investigate how to set up your server to serve the map imagery with those headers. You should also take a look at the crossOrigin option on your ol3 sources.

There is few solutions for CORS.
Very simple solution is to proxy OSM requests through your backend server (user <-> backend <-> OSM), but then we have little more server load.

Related

Building Multiple Tooltips From Db

I am converting my present map scripts from Google to Leaflet. I have a map with 5 layers, each with multiple locations that are stored in a Db table. I have two routines in the process. The first gathers the data from the Db and builds an XML file that is passed to the second. The second then parses the XML file and build individual L.marker content as follows:
for (var i = 0; i < numMarkers; i++) {
var mkrType = markers[i].getAttribute("type");
var mkrName = markers[i].getAttribute("name");
var mkrLat = markers[i].getAttribute("lat");
var mkrLon = markers[i].getAttribute("lon");
var mkrIcon = "files_images/mis_images/icon_tri_green.png"; break;
var mkrText = "<b>" + mkrName + "</b><br>Lat: " + mkrLat + " Lon: " + mkrLon;
L.marker([mkrLat, mkrLon], {icon: mkrIcon}).bindPopup(mkrText).addTo(cemeteries);
}
The script produces (Uncaught TypeError: t.addLayer is not a function) on the last line of the for loop (L.marker).
I figure the fault is that the loop/L.marker is within a function. If so, what and how do I pass what is need to make the code work.
TIA for any assistance
jdadwilson
My bad... Cemeteries was defined, I did not provide all of the function. Here it is...
function init_all_map(lyrActive) { 'use strict';
var cemeteries = L.layerGroup(),
churches = L.layerGroup(),
markers = L.layerGroup(),
schools = L.layerGroup(),
towns = L.layerGroup();
var overlays = { "Cemeteries": cemeteries, "Churches": churches, "Markers": markers, "Schools": schools, "Towns": towns };
var mbAttr = 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' + 'Imagery © Mapbox',
mbUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw',
msGeo = window.SERVER_PATH + 'files_geojson/geopoly_holmes.json';
var streets = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'),
county = new L.GeoJSON.AJAX(window.SERVER_PATH + "files_geojson/geopoly_holmes.json", {style: {color: "DarkGray", weight: 2, fillColor: ""}} );
var baseLayers = {"Streets": streets, "County": county};
var map = L.map('map_canvas_lg', {center: [CO_CENTER_LAT, CO_CENTER_LON], zoomControl: true, zoom: 10, minZoom: 8, maxZoom: 14,
layers: [streets, county, cemeteries, churches, markers, schools, towns]});
var lyrName = ["cemeteries", "churches", "markers", "schools", "towns"];
var lyrType = ["cem", "chu", "mkr", "sch", "twn"];
var numLays = lyrType.length;
var xmlType,
thisLayer,
newIcon;
for ( i=0; i<numLays; i++ ) {
//console.log("Layer: " + lyrType[i]);
thisLayer = lyrName[i];
console.log("thisLayer: " + thisLayer);
switch(lyrType[i]) {
case "cem":
xmlType = window.SERVER_PATH + "files_xml/xml_cemeteries.php";
newIcon = window.SERVER_PATH + "files_images/mis_images/icon_tri_green.png";
break;
//
// Other cases removed for brevity
//
} // End of switch
var mkrIcon = L.icon({ iconUrl: newIcon,shadowUrl: '',iconSize: [13,13],shadowSize: [0,0],iconAnchor: [7,13],shadowAnchor: [0,0],popupAnchor: [0,0]});
var xmlData = downloadUrl(xmlType, function(data) {
var xml = xmlParse(data);
var markers = xml.getElementsByTagName("marker");
var numMarkers = markers.length;
for (var j = 0; j < numMarkers; j++) {
var mkrType = markers[j].getAttribute("type");
var mkrName = markers[j].getAttribute("name");
var mkrLat = markers[j].getAttribute("lat");
var mkrLon = markers[j].getAttribute("lon");
var mkrText = "<b>" + mkrName + "</b><br>Lat: " + mkrLat + " Lon: " + mkrLon;
L.marker([mkrLat, mkrLon], {icon: mkrIcon}).bindPopup(mkrText).addTo(**lyrName[i]**);
} // End of Marker (j) loop
}); // End of downloadUrl
lyrName[i] = L.layerGroup().addTo(map);
} // End of layer (i) loop
L.control.layers(overlays).addTo(map);
window.dispatchEvent(new Event('resize'));
}
This line...
L.marker([mkrLat, mkrLon], {icon: mkrIcon}).bindPopup(mkrText).addTo(**lyrName[i]**);
throws the following error...
TypeError: Cannot read property 'addLayer' of undefined
If I change lyrName[i] to cemeteries the layer fills as desired.
Again TIA for any assistance.
jdadwilson
Your Layer cemeteries is not defined.
You can create a LayerGroup / FeatureGroup (is the same but with more function) with var cemeteries= L.featureGroup().addTo(map). Add this Line before your loop.
And then your code should work and the markers displayed on the map
Update
You are adding the marker to a string and not to the layer object. (I don't know what **lyrName[i]** are make, but it is not working...)
Try:
var lyrName = ["cemeteries", "churches", "markers", "schools", "towns"];
var lyrObjs = [cemeteries, churches, markers, schools, towns];
var lyrType = ["cem", "chu", "mkr", "sch", "twn"];
//...
L.marker([mkrLat, mkrLon], {icon: mkrIcon}).bindPopup(mkrText).addTo(lyrObjs[i]);

How to exclude workbooks of a Sheet when converting to PDF via script

function convertSpreadsheetToPdfNonIncremental(spreadsheetId, sheetName, pdfName) {
var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
spreadsheetId = spreadsheetId ? spreadsheetId : spreadsheet.getId()
var sheetId = sheetName ? spreadsheet.getSheetByName(sheetName).getSheetId() : null;
var pdfName = pdfName ? pdfName : spreadsheet.getName();
var parents = DriveApp.getFileById(spreadsheetId).getParents();
var folder = parents.hasNext() ? parents.next() : DriveApp.getRootFolder();
var url_base = spreadsheet.getUrl().replace(/edit$/,'');
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
// Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
+ '&gid=1012506648'
+ '&id=11NMFpk15pZ12RdXUsFRN8onueG9mhZqV57xLz_YoQY8'
// following parameters are optional...
+ '&size=letter' // paper size
+ '&portrait=false' // orientation, false for landscape
+ '&scale=4' //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&sheetnames=false&printtitle=false&pagenumbers=false' //hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&fzr=false'; // do not repeat row headers (frozen rows) on each page
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var file=DriveApp.getFileById('11NMFpk15pZ12RdXUsFRN8onueG9mhZqV57xLz_YoQY8');
var range = SpreadsheetApp.getActive().getRange('B3:C7');
var first = range.getCell(1, 1);
var last = range.getCell(5,2);
var pdfName = first.getValue() + ' Timesheet for Payroll Beginning ' + last.getDisplayValue();
var blob = response.getBlob().setName(pdfName +'.pdf');
folder.createFile(blob);
}
function convertSpreadsheetToPdfIncremental(spreadsheetId, sheetName, pdfName) {
var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
spreadsheetId = spreadsheetId ? spreadsheetId : spreadsheet.getId()
var sheetId = sheetName ? spreadsheet.getSheetByName(sheetName).getSheetId() : null;
var pdfName = pdfName ? pdfName : spreadsheet.getName();
var parents = DriveApp.getFileById(spreadsheetId).getParents();
var folder = parents.hasNext() ? parents.next() : DriveApp.getRootFolder();
var url_base = spreadsheet.getUrl().replace(/edit$/,'');
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
// Print either the entire Spreadsheet or the specified sheet if optSheetId1 is provided
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
// following parameters are optional...
+ '&size=letter' // paper size
+ '&portrait=false' // orientation, false for landscape
+ '&scale=4' //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&sheetnames=false&printtitle=false&pagenumbers=false' //hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&fzr=false'; // do not repeat row headers (frozen rows) on each page
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var file=DriveApp.getFileById('11NMFpk15pZ12RdXUsFRN8onueG9mhZqV57xLz_YoQY8');
var range = SpreadsheetApp.getActive().getRange('B3:C7');
var first = range.getCell(1, 1);
var last = range.getCell(5,2);
var pdfName = first.getValue() + ' Timesheet for Payroll Beginning ' + last.getDisplayValue();
var blob = response.getBlob().setName(pdfName +'.pdf');
folder.createFile(blob);
}
I have found, and been able to figure out the script, to convert either one workbook or all workbooks to PDF but can not find instruction/tips on how to convert more than one but no all, or exclude, workbooks when converting to PDF.
I have a Google Sheets spreadsheet that I want to convert all workbooks but one to PDF via script, and do not have the option of hiding the workbook that I don't want to convert.
Help please!

Google AdWords script issue

I am trying to set up an AdWords script for the first time but cannot get it to function properly. It is essentially supposed to crawl all of our clients' AdWords accounts, send all of the account information to a Google Sheet, and send me an email to let me know if there are any anomalies detected in any of the accounts. I have not had any luck with getting the info to send to the Google sheet, let a lone an email notification. This is the primary error I'm currently getting when I preview the script: TypeError: Cannot call method "getValue" of null. (line 510)
Here is the Google resource page (https://developers.google.com/adwords/scripts/docs/solutions/mccapp-account-anomaly-detector) for the script and the actual script itself that I'm using is below.
Any recommendations on how to get this to function properly would be greatly appreciated. Thank you!
// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* #name MCC Account Anomaly Detector
*
* #fileoverview The MCC Account Anomaly Detector alerts the advertiser whenever
* one or more accounts in a group of advertiser accounts under an MCC account
* is suddenly behaving too differently from what's historically observed. See
* https://developers.google.com/adwords/scripts/docs/solutions/mccapp-account-anomaly-detector
* for more details.
*
* #author AdWords Scripts Team [adwords-scripts#googlegroups.com]
*
* #version 1.4
*
* #changelog
* - version 1.4
* - Added conversions to tracked statistics.
* - version 1.3.2
* - Added validation for external spreadsheet setup.
* - version 1.3.1
* - Improvements to time zone handling.
* - version 1.3
* - Cleanup the script a bit for easier debugging and maintenance.
* - version 1.2
* - Added AdWords API report version.
* - version 1.1
* - Fix the script to work in accounts where there is no stats.
* - version 1.0
* - Released initial version.
*/
var SPREADSHEET_URL = 'https://docs.google.com/a/altitudemarketing.com/spreadsheets/d/1ELWZPcGLqf7n9GDnTx5o7xWOFZHVbgaLakeXAu5NY-E/edit?usp=sharing';
var CONFIG = {
// Uncomment below to include an account label filter
// ACCOUNT_LABEL: 'High Spend Accounts'
};
var CONST = {
FIRST_DATA_ROW: 12,
FIRST_DATA_COLUMN: 2,
MCC_CHILD_ACCOUNT_LIMIT: 50,
TOTAL_DATA_COLUMNS: 9
};
var STATS = {
'NumOfColumns': 4,
'Impressions':
{'Column': 3, 'Color': 'red', 'AlertRange': 'impressions_alert'},
'Clicks': {'Column': 4, 'Color': 'orange', 'AlertRange': 'clicks_alert'},
'Conversions':
{'Column': 5, 'Color': 'dark yellow 2', 'AlertRange': 'conversions_alert'},
'Cost': {'Column': 6, 'Color': 'yellow', 'AlertRange': 'cost_alert'}
};
var DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday'];
/**
* Configuration to be used for running reports.
*/
var REPORTING_OPTIONS = {
// Comment out the following line to default to the latest reporting version.
apiVersion: 'v201605'
};
function main() {
var account;
var alertText = [];
Logger.log('Using spreadsheet - %s.', SPREADSHEET_URL);
var spreadsheet = validateAndGetSpreadsheet(SPREADSHEET_URL);
spreadsheet.setSpreadsheetTimeZone(AdWordsApp.currentAccount().getTimeZone());
var dataRow = CONST.FIRST_DATA_ROW;
SheetUtil.setupData(spreadsheet);
Logger.log('MCC account: ' + mccManager.mccAccount().getCustomerId());
while (account = mccManager.next()) {
Logger.log('Processing account ' + account.getCustomerId());
alertText.push(processAccount(account, spreadsheet, dataRow));
dataRow++;
}
sendEmail(mccManager.mccAccount(), alertText, spreadsheet);
}
/**
* For each of Impressions, Clicks, Conversions, and Cost, check to see if the
* values are out of range. If they are, and no alert has been set in the
* spreadsheet, then 1) Add text to the email, and 2) Add coloring to the cells
* corresponding to the statistic.
*
* #return {string} the next piece of the alert text to include in the email.
*/
function processAccount(account, spreadsheet, startingRow) {
var sheet = spreadsheet.getSheets()[0];
var thresholds = SheetUtil.thresholds();
var today = AdWordsApp.report(SheetUtil.getTodayQuery(), REPORTING_OPTIONS);
var past = AdWordsApp.report(SheetUtil.getPastQuery(), REPORTING_OPTIONS);
var hours = SheetUtil.hourOfDay();
var todayStats = accumulateRows(today.rows(), hours, 1); // just one week
var pastStats = accumulateRows(past.rows(), hours, SheetUtil.weeksToAvg());
var alertText = ['Account ' + account.getCustomerId()];
var validWhite = ['', 'white', '#ffffff']; // these all count as white
// Colors cells that need alerting, and adds text to the alert email body.
function generateAlert(field, emailAlertText) {
// There are 2 cells to check, for Today's value and Past value
var bgRange = [
sheet.getRange(startingRow, STATS[field].Column, 1, 1),
sheet.getRange(startingRow, STATS[field].Column + STATS.NumOfColumns,
1, 1)
];
var bg = [bgRange[0].getBackground(), bgRange[1].getBackground()];
// If both backgrounds are white, change background Colors
// and update most recent alert time.
if ((-1 != validWhite.indexOf(bg[0])) &&
(-1 != validWhite.indexOf(bg[1]))) {
bgRange[0].setBackground([[STATS[field]['Color']]]);
bgRange[1].setBackground([[STATS[field]['Color']]]);
spreadsheet.getRangeByName(STATS[field]['AlertRange']).
setValue('Alert at ' + hours + ':00');
alertText.push(emailAlertText);
}
}
if (thresholds.Impressions &&
todayStats.Impressions < pastStats.Impressions * thresholds.Impressions) {
generateAlert('Impressions',
' Impressions are too low: ' + todayStats.Impressions +
' Impressions by ' + hours + ':00, expecting at least ' +
parseInt(pastStats.Impressions * thresholds.Impressions));
}
if (thresholds.Clicks &&
todayStats.Clicks < (pastStats.Clicks * thresholds.Clicks).toFixed(1)) {
generateAlert('Clicks',
' Clicks are too low: ' + todayStats.Clicks +
' Clicks by ' + hours + ':00, expecting at least ' +
(pastStats.Clicks * thresholds.Clicks).toFixed(1));
}
if (thresholds.Conversions &&
todayStats.Conversions <
(pastStats.Conversions * thresholds.Conversions).toFixed(1)) {
generateAlert(
'Conversions',
' Conversions are too low: ' + todayStats.Conversions +
' Conversions by ' + hours + ':00, expecting at least ' +
(pastStats.Conversions * thresholds.Conversions).toFixed(1));
}
if (thresholds.Cost &&
todayStats.Cost > (pastStats.Cost * thresholds.Cost).toFixed(2)) {
generateAlert(
'Cost',
' Cost is too high: ' + todayStats.Cost + ' ' +
account.getCurrencyCode() + ' by ' + hours +
':00, expecting at most ' +
(pastStats.Cost * thresholds.Cost).toFixed(2));
}
// If no alerts were triggered, we will have only the heading text. Remove it.
if (alertText.length == 1) {
alertText = [];
}
var dataRows = [[
account.getCustomerId(), todayStats.Impressions, todayStats.Clicks,
todayStats.Conversions, todayStats.Cost, pastStats.Impressions.toFixed(0),
pastStats.Clicks.toFixed(1), pastStats.Conversions.toFixed(1),
pastStats.Cost.toFixed(2)
]];
sheet.getRange(startingRow, CONST.FIRST_DATA_COLUMN,
1, CONST.TOTAL_DATA_COLUMNS).setValues(dataRows);
return alertText;
}
var SheetUtil = (function() {
var thresholds = {};
var upToHour = 1; // default
var weeks = 26; // default
var todayQuery = '';
var pastQuery = '';
var setupData = function(spreadsheet) {
Logger.log('Running setupData');
spreadsheet.getRangeByName('date').setValue(new Date());
spreadsheet.getRangeByName('account_id').setValue(
mccManager.mccAccount().getCustomerId());
var getThresholdFor = function(field) {
thresholds[field] = parseField(spreadsheet.
getRangeByName(field).getValue());
};
getThresholdFor('Impressions');
getThresholdFor('Clicks');
getThresholdFor('Conversions');
getThresholdFor('Cost');
var now = new Date();
// Basic reporting statistics are usually available with no more than a 3-hour
// delay.
var upTo = new Date(now.getTime() - 3 * 3600 * 1000);
upToHour = parseInt(getDateStringInTimeZone('h', upTo));
spreadsheet.getRangeByName('timestamp').setValue(
DAYS[getDateStringInTimeZone('u', now)] + ', ' + upToHour + ':00');
if (upToHour == 1) {
// First run of the day, clear existing alerts.
spreadsheet.getRangeByName(STATS['Clicks']['AlertRange']).clearContent();
spreadsheet.getRangeByName(STATS['Impressions']['AlertRange']).
clearContent();
spreadsheet.getRangeByName(STATS['Conversions']['AlertRange'])
.clearContent();
spreadsheet.getRangeByName(STATS['Cost']['AlertRange']).clearContent();
// Reset background and font Colors for all data rows.
var bg = [];
var ft = [];
var bg_single = [
'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white',
'white'
];
var ft_single = [
'black', 'black', 'black', 'black', 'black', 'black', 'black', 'black',
'black'
];
// Construct a 50-row array of colors to set.
for (var a = 0; a < CONST.MCC_CHILD_ACCOUNT_LIMIT; ++a) {
bg.push(bg_single);
ft.push(ft_single);
}
var dataRegion = spreadsheet.getSheets()[0].getRange(
CONST.FIRST_DATA_ROW, CONST.FIRST_DATA_COLUMN,
CONST.MCC_CHILD_ACCOUNT_LIMIT, CONST.TOTAL_DATA_COLUMNS);
dataRegion.setBackgrounds(bg);
dataRegion.setFontColors(ft);
}
var weeksStr = spreadsheet.getRangeByName('weeks').getValue();
weeks = parseInt(weeksStr.substring(0, weeksStr.indexOf(' ')));
var dateRangeToCheck = getDateStringInPast(0, upTo);
var dateRangeToEnd = getDateStringInPast(1, upTo);
var dateRangeToStart = getDateStringInPast(1 + weeks * 7, upTo);
var fields = 'HourOfDay, DayOfWeek, Clicks, Impressions, Conversions, Cost';
todayQuery = 'SELECT ' + fields +
' FROM ACCOUNT_PERFORMANCE_REPORT DURING ' + dateRangeToCheck + ',' +
dateRangeToCheck;
pastQuery = 'SELECT ' + fields +
' FROM ACCOUNT_PERFORMANCE_REPORT WHERE DayOfWeek=' +
DAYS[getDateStringInTimeZone('u', now)].toUpperCase() +
' DURING ' + dateRangeToStart + ',' + dateRangeToEnd;
};
var getThresholds = function() { return thresholds; };
var getHourOfDay = function() { return upToHour; };
var getWeeksToAvg = function() { return weeks; };
var getPastQuery = function() { return pastQuery; };
var getTodayQuery = function() { return todayQuery; };
// The SheetUtil public interface.
return {
setupData: setupData,
thresholds: getThresholds,
hourOfDay: getHourOfDay,
weeksToAvg: getWeeksToAvg,
getPastQuery: getPastQuery,
getTodayQuery: getTodayQuery
};
})();
function sendEmail(account, alertTextArray, spreadsheet) {
var bodyText = '';
alertTextArray.forEach(function(alertText) {
// When zero alerts, this is an empty array, which we don't want to add.
if (alertText.length == 0) { return }
bodyText += alertText.join('\n') + '\n\n';
});
bodyText = bodyText.trim();
var email = spreadsheet.getRangeByName('email').getValue();
if (bodyText.length > 0 && email && email.length > 0 &&
email != 'foo#example.com') {
Logger.log('Sending Email');
MailApp.sendEmail(email,
'AdWords Account ' + account.getCustomerId() + ' misbehaved.',
'Your account ' + account.getCustomerId() +
' is not performing as expected today: \n\n' +
bodyText + '\n\n' +
'Log into AdWords and take a look: ' +
'adwords.google.com\n\nAlerts dashboard: ' +
SPREADSHEET_URL);
}
else if (bodyText.length == 0) {
Logger.log('No alerts triggered. No email being sent.');
}
}
function toFloat(value) {
value = value.toString().replace(/,/g, '');
return parseFloat(value);
}
function parseField(value) {
if (value == 'No alert') {
return null;
} else {
return toFloat(value);
}
}
function accumulateRows(rows, hours, weeks) {
var result = {Clicks: 0, Impressions: 0, Conversions: 0, Cost: 0};
while (rows.hasNext()) {
var row = rows.next();
var hour = row['HourOfDay'];
if (hour < hours) {
result = addRow(row, result, 1 / weeks);
}
}
return result;
}
function addRow(row, previous, coefficient) {
if (!coefficient) {
coefficient = 1;
}
if (!row) {
row = {Clicks: 0, Impressions: 0, Conversions: 0, Cost: 0};
}
if (!previous) {
previous = {Clicks: 0, Impressions: 0, Conversions: 0, Cost: 0};
}
return {
Clicks: parseInt(row['Clicks']) * coefficient + previous.Clicks,
Impressions:
parseInt(row['Impressions']) * coefficient + previous.Impressions,
Conversions:
parseInt(row['Conversions']) * coefficient + previous.Conversions,
Cost: toFloat(row['Cost']) * coefficient + previous.Cost
};
}
function checkInRange(today, yesterday, coefficient, field) {
var yesterdayValue = yesterday[field] * coefficient;
if (today[field] > yesterdayValue * 2) {
Logger.log('' + field + ' too much');
} else if (today[field] < yesterdayValue / 2) {
Logger.log('' + field + ' too little');
}
}
/**
* Produces a formatted string representing a date in the past of a given date.
*
* #param {number} numDays The number of days in the past.
* #param {date} date A date object. Defaults to the current date.
* #return {string} A formatted string in the past of the given date.
*/
function getDateStringInPast(numDays, date) {
date = date || new Date();
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var past = new Date(date.getTime() - numDays * MILLIS_PER_DAY);
return getDateStringInTimeZone('yyyyMMdd', past);
}
/**
* Produces a formatted string representing a given date in a given time zone.
*
* #param {string} format A format specifier for the string to be produced.
* #param {date} date A date object. Defaults to the current date.
* #param {string} timeZone A time zone. Defaults to the account's time zone.
* #return {string} A formatted string of the given date in the given time zone.
*/
function getDateStringInTimeZone(format, date, timeZone) {
date = date || new Date();
timeZone = timeZone || AdWordsApp.currentAccount().getTimeZone();
return Utilities.formatDate(date, timeZone, format);
}
/**
* Module that deals with fetching and iterating through multiple accounts.
*
* #return {object} callable functions corresponding to the available
* actions. Specifically, it currently supports next, current, mccAccount.
*/
var mccManager = (function() {
var accountIterator;
var mccAccount;
var currentAccount;
// Private one-time init function.
var init = function() {
var accountSelector = MccApp.accounts();
// Use this to limit the accounts that are being selected in the report.
if (CONFIG.ACCOUNT_LABEL) {
accountSelector.withCondition("LabelNames CONTAINS '" +
CONFIG.ACCOUNT_LABEL + "'");
}
accountSelector.withLimit(CONST.MCC_CHILD_ACCOUNT_LIMIT);
accountIterator = accountSelector.get();
mccAccount = AdWordsApp.currentAccount(); // save the mccAccount
currentAccount = AdWordsApp.currentAccount();
};
/**
* After calling this, AdWordsApp will have the next account selected.
* If there are no more accounts to process, re-selects the original
* MCC account.
*
* #return {AdWordsApp.Account} The account that has been selected.
*/
var getNextAccount = function() {
if (accountIterator.hasNext()) {
currentAccount = accountIterator.next();
MccApp.select(currentAccount);
return currentAccount;
}
else {
MccApp.select(mccAccount);
return null;
}
};
/**
* Returns the currently selected account. This is cached for performance.
*
* #return {AdWords.Account} The currently selected account.
*/
var getCurrentAccount = function() {
return currentAccount;
};
/**
* Returns the original MCC account.
*
* #return {AdWords.Account} The original account that was selected.
*/
var getMccAccount = function() {
return mccAccount;
};
// Set up internal variables; called only once, here.
init();
// Expose the external interface.
return {
next: getNextAccount,
current: getCurrentAccount,
mccAccount: getMccAccount
};
})();
/**
* Validates the provided spreadsheet URL and email address
* to make sure that they're set up properly. Throws a descriptive error message
* if validation fails.
*
* #param {string} spreadsheeturl The URL of the spreadsheet to open.
* #return {Spreadsheet} The spreadsheet object itself, fetched from the URL.
* #throws {Error} If the spreadsheet URL or email hasn't been set
*/
function validateAndGetSpreadsheet(spreadsheeturl) {
if (spreadsheeturl == 'YOUR_SPREADSHEET_URL') {
throw new Error('Please specify a valid Spreadsheet URL. You can find' +
' a link to a template in the associated guide for this script.');
}
var spreadsheet = SpreadsheetApp.openByUrl(spreadsheeturl);
var email = spreadsheet.getRangeByName('email').getValue();
if ('foo#example.com' == email) {
throw new Error('Please either set a custom email address in the' +
' spreadsheet, or set the email field in the spreadsheet to blank' +
' to send no email.');
}
return spreadsheet;
}

Ipad not showing canvas lines properly

I have created small script for vision testing. I posted part of it on https://jsfiddle.net/jaka_87/bpadyanh/
The theory behind it: Canvas is filled with pattern.In each pattern there are 3 lines drawn. Two black ones with the white one in the middle. The white line has 2*with of one black line. When width of this lines is so small that our eye cant distinguish between these three we see only gray background (even thou the lines are still there).
I tested it on few computers. On most of them it works well (thou i saw some strange patterns on some of the older ones - one column of vertical white lines then 2-3 dark column then white one....) I was assuming that it has do do with the display/graphic card or something similar. I tested it on some some mobile devices. It works fine on my Nexus 7 and Moto G, but not on my Transformer Prime pad (strange pattern like described before - for which again I blame the tablet).
It looks absolutely horrible (by far the worst from all tested) on my Ipad and my friends Iphone. I was expecting the best result there since they are known for very good screens but the results are horrible. When the lines are wide enough its OK but when they get narrower they are merged together to one either black or white line - not shown separately.
Is there any way to fix that so it would work on iOS ??
var povecava2 = "0.04226744186046511";
var izmerjeno =1;
var razmak =3.5;
var contrast = 1;
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
// širina canvasa
ctx.canvas.width = window.innerWidth-23;
ctx.canvas.height = window.innerHeight-70;
var sirinaopto=Math.round(200*izmerjeno*povecava2*razmak);
if(sirinaopto & 1){sirinaopto=sirinaopto;}else{ sirinaopto=sirinaopto+1;} // če je širina optotipa soda ali liha
var enota4 =((0.19892970392*130*izmerjeno*povecava2)/4).toFixed(2); // 1 kotna minuta
var center= Math.round((ctx.canvas.width-(sirinaopto))/2);
// kolkrat gre v višino
var kolkratgre = Math.floor(ctx.canvas.height/(sirinaopto));
var visina2= sirinaopto*kolkratgre;
// kolkrat gre v širino
var kolkratgrehor = Math.ceil(ctx.canvas.width/sirinaopto); if(kolkratgrehor % 2 == 0) { var kolkratgrehor=kolkratgrehor-1; }
var zacetek = (ctx.canvas.width-(kolkratgrehor*sirinaopto))/2;
ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle="rgb(140,140,140)";
ctx.fill();
// 90 stopinj
var canvasPattern0 = document.createElement("canvas");
canvasPattern0.width = sirinaopto;
canvasPattern0.height = sirinaopto;
var contextPattern0 = canvasPattern0.getContext("2d");
contextPattern0.mozImageSmoothingEnabled = false;
contextPattern0.imageSmoothingEnabled = false;
contextPattern0.translate((canvasPattern0.width/2)-(enota4*2),(canvasPattern0.width/2)-(10*enota4));
contextPattern0.beginPath();
contextPattern0.globalAlpha = contrast;
contextPattern0.moveTo(enota4/2,0);
contextPattern0.lineTo(enota4/2,20*enota4);
contextPattern0.lineWidth=enota4;
contextPattern0.strokeStyle = 'black';
contextPattern0.stroke();
contextPattern0.closePath();
contextPattern0.beginPath();
contextPattern0.globalAlpha = contrast;
contextPattern0.moveTo(enota4*2,0);
contextPattern0.lineTo(enota4*2,20*enota4);
contextPattern0.lineWidth=enota4*2;
contextPattern0.strokeStyle = 'white';
contextPattern0.stroke();
contextPattern0.closePath();
contextPattern0.beginPath();
contextPattern0.globalAlpha = contrast;
contextPattern0.moveTo(enota4*3.5,0);
contextPattern0.lineTo(enota4*3.5,20*enota4);
contextPattern0.lineWidth=enota4;
contextPattern0.strokeStyle = 'black';
contextPattern0.stroke();
contextPattern0.closePath();
// 0 stopinj
var canvasPattern1 = document.createElement("canvas");
canvasPattern1.width = sirinaopto;canvasPattern1.height = sirinaopto;
var contextPattern1 = canvasPattern1.getContext("2d");
contextPattern1.translate(sirinaopto/2, sirinaopto/2);
contextPattern1.rotate(90*Math.PI/180);
contextPattern1.drawImage(canvasPattern0, sirinaopto*(-0.5), sirinaopto*(-0.5));
contextPattern1.save();
var imagesLoaded = [];
imagesLoaded.push(canvasPattern0);
imagesLoaded.push(canvasPattern1);
var randomPattern = function(imgWidth, imgHeight, areaWidth, areaHeight) {
// either set a defined width/height for our images, or use the first one's
imgWidth = sirinaopto;
imgHeight = sirinaopto;
// restrict the randmoness size by using an areaWidth/Height
areaWidth = ctx.canvas.width;
areaHeight = visina2;
// create a buffer canvas
var patternCanvas = canvas.cloneNode(true);
var patternCtx = patternCanvas.getContext('2d');
patternCanvas.width = areaWidth;
patternCanvas.height = areaHeight;
// var xloops = Math.ceil(areaWidth / imgWidth);
var xloops = Math.ceil(areaWidth / imgWidth); if(xloops % 2 == 0) { var xloops=xloops-1; }
var yloops = Math.ceil(areaHeight / imgHeight);
//alert(xloops);
for (var xpos = 0; xpos < xloops; xpos++) {
for (var ypos = 0; ypos < yloops; ypos++) {
var img = imagesLoaded[Math.floor(Math.random() * imagesLoaded.length)];
patternCtx.drawImage(img, (xpos * imgWidth)+zacetek, (ypos * imgHeight), imgWidth, imgHeight);
}
}
// create a pattern from this randomly created image
return patternCtx.createPattern(patternCanvas, 'repeat');
}
var draw = function() {
//create the random pattern (should be moved out of the draw)
var patt = randomPattern(sirinaopto,sirinaopto);
ctx.fillStyle = patt;
ctx.fillRect(0,0,ctx.canvas.width, visina2)
};
draw();

Word wrap in generated PDF (using jsPDF)?

what I'm doing is using jsPDF to create a PDF of the graph I generated. However, I am not sure how to wrap the title (added by using the text() function). The length of the title will vary from graph to graph. Currently, my titles are running off the page. Any help would be appreciated!
This is the code i have so far:
var doc = new jsPDF();
doc.setFontSize(18);
doc.text(15, 15, reportTitle);
doc.addImage(outputURL, 'JPEG', 15, 40, 180, 100);
doc.save(reportTitle);
Nothing to keep the reportTitle from running off the page
Okay I've solved this. I used the jsPDF function, splitTextToSize(text, maxlen, options). This function returns an array of strings. Fortunately, the jsPDF text() function, which is used to write to the document, accepts both strings and arrays of strings.
var splitTitle = doc.splitTextToSize(reportTitle, 180);
doc.text(15, 20, splitTitle);
You can just use the optional argument maxWidth from the text function.
doc.text(15, 15, reportTitle, { maxWidth: 40 });
That will split the text once it reaches the maxWidth and start on the next line.
Auto-paging and text wrap issue in JSPDF can achieve with following code
var splitTitle = doc.splitTextToSize($('#textarea').val(), 270);
var pageHeight = doc.internal.pageSize.height;
doc.setFontType("normal");
doc.setFontSize("11");
var y = 7;
for (var i = 0; i < splitTitle.length; i++) {
if (y > 280) {
y = 10;
doc.addPage();
}
doc.text(15, y, splitTitle[i]);
y = y + 7;
}
doc.save('my.pdf');
To wrap long string of text to page use this code:
var line = 25 // Line height to start text at
var lineHeight = 5
var leftMargin = 20
var wrapWidth = 180
var longString = 'Long text string goes here'
var splitText = doc.splitTextToSize(longString, wrapWidth)
for (var i = 0, length = splitText.length; i < length; i++) {
// loop thru each line and increase
doc.text(splitText[i], leftMargin, line)
line = lineHeight + line
}
If you need to dynamically add new lines you want to access the array returned by doc.splitTextToSize and then add more vertical space as you go through each line:
var y = 0, lengthOfPage = 500, text = [a bunch of text elements];
//looping thru each text item
for(var i = 0, textlength = text.length ; i < textlength ; i++) {
var splitTitle = doc.splitTextToSize(text[i], lengthOfPage);
//loop thru each line and output while increasing the vertical space
for(var c = 0, stlength = splitTitle.length ; c < stlength ; c++){
doc.text(y, 20, splitTitle[c]);
y = y + 10;
}
}
Working Helper function
Here's a complete helper function based on the answers by #KB1788 and #user3749946:
It includes line wrap, page wrap, and some styling control:
(Gist available here)
function addWrappedText({text, textWidth, doc, fontSize = 10, fontType = 'normal', lineSpacing = 7, xPosition = 10, initialYPosition = 10, pageWrapInitialYPosition = 10}) {
var textLines = doc.splitTextToSize(text, textWidth); // Split the text into lines
var pageHeight = doc.internal.pageSize.height; // Get page height, well use this for auto-paging
doc.setFontType(fontType);
doc.setFontSize(fontSize);
var cursorY = initialYPosition;
textLines.forEach(lineText => {
if (cursorY > pageHeight) { // Auto-paging
doc.addPage();
cursorY = pageWrapInitialYPosition;
}
doc.text(xPosition, cursorY, lineText);
cursorY += lineSpacing;
})
}
Usage
// All values are jsPDF global units (default unit type is `px`)
const doc = new jsPDF();
addWrappedText({
text: "'Twas brillig, and the slithy toves...", // Put a really long string here
textWidth: 220,
doc,
// Optional
fontSize: '12',
fontType: 'normal',
lineSpacing: 7, // Space between lines
xPosition: 10, // Text offset from left of document
initialYPosition: 30, // Initial offset from top of document; set based on prior objects in document
pageWrapInitialYPosition: 10 // Initial offset from top of document when page-wrapping
});
When we use linebreak in jsPDF we get an error stating b.match is not defined, to solve this error just unminify the js and replace b.match with String(b).match and u will get this error twice just replace both and then we get c.split is not defined just do the same in this case replace it with String(c).match and we are done. Now you can see line breaks in you pdf. Thank you

Resources