UNPKG

fluentreports

Version:

A simple, Fluent API for creating PDF Reports

1,239 lines (1,132 loc) 219 kB
/* -------------------------------------- (c)2012-2018, Kellpro, Inc. (c)2016-2023, Master Technology -------------------------------------- FluentReports is under The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //noinspection ThisExpressionReferencesGlobalObjectJS,JSHint /** * @module fluentReports * @author Nathanael Anderson * @contributors Mark Getz, Alan Henager, Beau West, Marcus Christensson * @copyright 2012-2018, Kellpro Inc. * @copyright 2016-2022, Master Technology. * @license MIT */ (function (_global) { "use strict"; // Layout: /* Report -> Section -> DataSet -> Group -> (Optional) Sub-Report) -> Group -> ... */ // ------------------------------------------------------ // Helper Functions // ------------------------------------------------------ /** * Gets a setting from a setting collection, checks for the normal case; and then a lower case version * @param settingsObject * @param setting * @param defaultValue * @return {*} defaultValue if no setting exists */ function getSettings(settingsObject, setting, defaultValue) { if (!settingsObject) { return (defaultValue); } if (typeof settingsObject[setting] !== 'undefined') { return settingsObject[setting]; } else { const lSetting = setting.toLowerCase(); if (typeof settingsObject[lSetting] !== 'undefined') { return settingsObject[lSetting]; } } return defaultValue; } /** * This creates a lower case version of the prototypes * @param prototype */ function lowerPrototypes(prototype) { let proto, lowerProto; for (proto in prototype) { if (prototype.hasOwnProperty(proto)) { // Don't lowercase internal prototypes if (proto[0] === '_') { continue; } lowerProto = proto.toLowerCase(); // If the prototype is already lower cased, then we skip if (lowerProto === proto) { continue; } // verify it is a function if (typeof prototype[proto] === "function") { prototype[lowerProto] = prototype[proto]; } } } } /** Debug Code **/ function printStructure(reportObject, level, outputType) { if (reportObject === null) { return; } let i, j, added = (2 * level), pad = "", spad = ''; for (i = 0; i < added; i++) { pad += "-"; spad += " "; } const loopChildren = () => { if (reportObject._child) { printStructure(reportObject._child, level + 1, outputType); } else if (reportObject._children) { for (j = 0; j < reportObject._children.length; j++) { printStructure(reportObject._children[j], level + 1, outputType); } } }; if (reportObject._isReport) { if (reportObject._parent) { console.log(pad + "> Subreport (Height Exempt?)"); } else { console.log(pad + "> Report (Height Exempt?)"); } } else if (reportObject._isSection) { console.log(pad + "> Section"); } else if (reportObject._isDataSet) { console.log(pad + "> DataSet"); } else if (reportObject._isGroup) { console.log(pad + "> Group = " + reportObject._groupOnField); if (reportObject._math.length > 0) { console.log(pad + "= Totaling:", reportObject._math); } } else { console.log(pad + "> Unknown"); } if (reportObject._theader !== null && reportObject._theader !== undefined) { console.log(spad + " | Has Title Header ", typeof reportObject._theader._part === "function" ? reportObject._theader._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._theader._partHeight > 0 ? reportObject._theader._partHeight : '', reportObject._theader._isHeightExempt); } if (reportObject._header !== null && reportObject._header !== undefined) { if (reportObject._isReport) { console.log(spad + " | Has Page Header", typeof reportObject._header._part === "function" ? reportObject._header._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._header._partHeight > 0 ? reportObject._header._partHeight : '', reportObject._header._isHeightExempt); } else { console.log(spad + " | Has Header", typeof reportObject._header._part === "function" ? reportObject._header._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._header._partHeight > 0 ? reportObject._header._partHeight : '', reportObject._header._isHeightExempt); } } if (reportObject._detail !== null && reportObject._detail !== undefined) { console.log(spad + " | Has Detail", reportObject._renderDetail === reportObject._renderAsyncDetail ? "(Async)" : reportObject._renderDetail === reportObject._renderSyncDetail ? "(Sync)" : reportObject._renderDetail === reportObject._renderBandDetail ? "(Auto Band)" : reportObject._renderDetail === reportObject._renderStringDetail ? "(Auto String)" : "Unknown"); } if (outputType) { loopChildren(); } if (reportObject._footer !== null && reportObject._footer !== undefined) { if (reportObject._isReport) { console.log(spad + " | Has Page Footer", typeof reportObject._footer._part === "function" ? reportObject._footer._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._footer._partHeight > 0 ? reportObject._footer._partHeight : '', reportObject._footer._isHeightExempt); } else { console.log(spad + " | Has Footer", typeof reportObject._footer._part === "function" ? reportObject._footer._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._footer._partHeight > 0 ? reportObject._footer._partHeight : '', reportObject._footer._isHeightExempt); } } if (reportObject._tfooter !== null && reportObject._tfooter !== undefined) { console.log(spad + " | Has Summary Footer", typeof reportObject._tfooter._part === "function" ? reportObject._tfooter._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._tfooter._partHeight > 0 ? reportObject._tfooter._partHeight : '', reportObject._tfooter._isHeightExempt); } if (!outputType) { loopChildren(); } } /** * Returns true if object is an array object * @param obj * @return {Boolean} True or False */ function isArray(obj) { return (Object.prototype.toString.apply(obj) === '[object Array]'); } /** * returns true if this is a number * @param num * @return {Boolean} */ function isNumber(num) { return ((typeof num === 'string' || typeof num === 'number') && !isNaN(num - 0) && num !== '' ); } /** * Clones the data -- this is a simple clone, it does *NOT* do any really DEEP copies; * but nothing in the report module needs a deep copy. * @param value * @return {*} */ function clone(value) { let key, target = {}, i, aTarget = []; if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || Object.prototype.toString.call(value) === '[object Date]') { return value; } if (isArray(value)) { for (i = 0; i < value.length; i++) { aTarget.push(clone(value[i])); } return (aTarget); } else if (typeof aTarget === "object") { for (key in value) { if (value.hasOwnProperty(key)) { target[key] = value[key]; } } return target; } else { // Currently this path is not used in the clone... return JSON.parse(JSON.stringify(value)); } } /** * Generic Error function that can be overridden with your own error code */ function error() { if (!console || !console.error || arguments.length === 0) { return; } console.error.apply(console, arguments); } /** * @class ReportError * @desc This is a constructor for error details that are returned by fluentreports * @param detailsObject - detail Object, generally including some mix of error, error.stack, and an error code * @constructor */ function ReportError(detailsObject) { for (let key in detailsObject) { if (!detailsObject.hasOwnProperty(key)) { continue; } this[key] = detailsObject[key]; } } /** * This is a callback that just prints any errors, used for places a callback may not have been passed in. * @param err */ function dummyCallback(err) { if (err) { Report.error(err); } } /** * This does a loop, used for Async code * @param total number of loops * @param runFunction - this is the function that will be called for each iteration * @param doneCallback - this is called when the loop is done */ function startLoopingAsync(total, runFunction, doneCallback) { let counter = -1; const callbackLoop = () => { counter++; if (counter < total) { // Unwind this stack every so often if (counter % 10 === 0) { setTimeout(() => { runFunction(counter, callbackLoop); }, 0); } else { runFunction(counter, callbackLoop); } } else { doneCallback(); } }; callbackLoop(); } /** * This does a loop, used for Sync code * @param total number of loops * @param runFunction - this is the function that will be called for each iteration * @param doneCallback - this is called when the loop is done */ function startLoopingSync(total, runFunction, doneCallback) { let counter= 0; let hasAnotherLoop = true; const callbackLoop = (skipInc) => { if (skipInc !== true) { counter++; } if (counter < total) { // Unwind this stack every so ofter if (skipInc !== true && counter % 10 === 0) { // Technically we don't have to reset this to true; as it is already true; but this is so that // this function is readable by use mere humans several months from here. hasAnotherLoop = true; } else { runFunction(counter, callbackLoop); } } else { hasAnotherLoop = false; } }; while (hasAnotherLoop) { callbackLoop(true); } doneCallback(); } const reportRenderingMode = {UNDEFINED: 0, SYNC: 1, ASYNC: 2}; // If any are added to this, you need to add the function, and update _calcTotals and _clearTotals, const mathTypes = {SUM: 1, AVERAGE: 2, MIN: 3, MAX: 4, COUNT: 5}; const dataTypes = {NORMAL: 0, PAGEABLE: 1, FUNCTIONAL: 2, PLAINOLDDATA: 3, PARENT: 4}; // ------------------------------------------------------- // Report Objects // ------------------------------------------------------- /** * ReportSection * @class ReportSection * @desc This is a Report Section that allows multiple DataSets for laying out a report. * @param parent object, typically another section, group or report object * @constructor * @alias ReportSection * @memberof Report */ function ReportSection(parent) { this._children = []; this._parent = parent; } /** * ReportRenderer * @class ReportRenderer * @desc This is the Wrapper around the PDFKit, and could be used to wrap any output library. * @classdesc this is the RENDERER class passed into your callbacks during report generation. * @constructor * @alias ReportRenderer */ function ReportRenderer(primaryReport, options) { this.totals = {}; this._priorValues = {}; this._pageHasRendering = 0; this._pageHeaderRendering = 0; this._curBand = []; this._curBandOffset = 0; this._primaryReport = primaryReport; this._pageBreaking = false; this._skipASYNCCheck = false; this._landscape = false; this._paper = "letter"; this._margins = 72; this._lineWidth = 1; this._level = 0; this._totalLevels = 0; this._negativeParentheses = false; this._heightOfString = 0; this._graphicState = []; this._fillColor = "black"; this._strokeColor = "black"; this._fillOpacity = 1; this._rotated = 0; this._height = 0; this._reportHeight = 0; this._printedLines = []; this._pageNumbers = []; this._reportRenderMode = reportRenderingMode.UNDEFINED; let opt = {}; if (options) { if (options.paper) { this._paper = options.paper; if (this._paper !== "letter") { opt.size = this._paper; } } if (options.landscape) { this._landscape = true; opt.layout = "landscape"; } if (options.margins && options.margins !== this._margins) { this._margins = options.margins; if (typeof options.margins === 'number') { opt.margin = options.margins; } else { opt.margins = options.margins; } } if (options.fonts) { this._fonts = options.fonts; } if (options.registeredFonts) { this._registeredFonts = options.registeredFonts; } if (options.info) { opt.info = options.info; } } if (!this._fonts) { this._fonts = clone(Report._indexedFonts); } if (!this._registeredFonts) { this._registeredFonts = {}; } this._PDF = new this._PDFKit(opt); this._heightOfString = this._PDF.currentLineHeight(true); this._height = this._reportHeight = this._PDF.page.maxY(); this._PDF.page.height = 99999; for (let key in this._registeredFonts) { if (!this._registeredFonts.hasOwnProperty(key)) { continue; } for (let style in this._registeredFonts[key]) { if (!this._registeredFonts[key].hasOwnProperty(style)) { continue; } if (style === 'normal') { this._PDF.registerFont(key, this._registeredFonts[key][style]); } else { this._PDF.registerFont(key+'-'+style, this._registeredFonts[key][style]); } } } // This is a PDFDoc emulated page wrapper so that we can detect how it will wrap things. const lwDoc = this._LWDoc = { count: 0, pages: 1, x: this._PDF.page.margins.left, y: this._PDF.page.margins.top, page: this._PDF.page, _PDF: this._PDF, currentLineHeight: function (val) { //noinspection JSPotentiallyInvalidUsageOfThis return this._PDF.currentLineHeight(val); }, widthOfString: function (d, o) { let splitString = d.split(' '), curWord, wos = 0, wordLength; for (let i = 0; i < splitString.length; ++i) { curWord = splitString[i]; if ((i + 1) !== splitString.length) { curWord += ' '; } //noinspection JSPotentiallyInvalidUsageOfThis wordLength = this._PDF.widthOfString(curWord, o); wos += wordLength; } return wos; }, addPage: function () { this.pages++; //noinspection JSPotentiallyInvalidUsageOfThis this.x = this._PDF.page.margins.left; //noinspection JSPotentiallyInvalidUsageOfThis this.y = this._PDF.page.margins.top; }, reset: function () { this.count = 0; this.pages = 0; this.addPage(); } }; // Create a new Line Wrapper Object, this allows us to handle Bands this._LineWrapper = new this._LineWrapperObject(lwDoc,{width:this._PDF.page.width - this._PDF.page.margins.right - this._PDF.page.margins.left, columns:1, columnGap: 18}); this._LineWrapper.on('line', () => { lwDoc.count++; }); // Create the Print wrapper; this allows us to wrap long print() calls onto multiple lines. this._PrintWrapper = new this._LineWrapperObject(lwDoc,{width:this._PDF.page.width - this._PDF.page.margins.right - this._PDF.page.margins.left, columns:1, columnGap: 18}); this._PrintWrapper.on('line', (line, options) => { this._printedLines.push({L:line, O: options}); }); } /** * @class ReportHeaderFooter * @desc Creates a Object for tracking Header/Footer instances * @constructor * @alias ReportHeaderFooter * @memberof Report * @param isHeader * @param {boolean} [isSizeExempt] - is Size Exempt, this ONLY applies to page footers; as we don't want to "break" the page on a page footer. */ function ReportHeaderFooter(isHeader, isSizeExempt) { this._part = null; this._isFunction = false; this._partHeight = -1; //noinspection JSUnusedGlobalSymbols this._partWidth = -1; this._pageBreakBefore = false; this._pageBreakAfter = false; this._isHeader = isHeader; // This only applies to Page FOOTERS, and the final summary FOOTER. These are the only items that won't cause a page-break before/during printing. // Normally this is not a issue; but some people might use absolute Y coords and end up overflowing the page in the footer; // which then causes a major glitch in the rendering. So instead we are just going to let the footer overflow the page and ignore the rest of the footer. // This is a much "cleaner" looking solution. this._isHeightExempt = isHeader ? false : !!isSizeExempt; } /** * ReportGroup * @class ReportGroup * @desc This creates a Report Grouping Section * @classdesc This Creates a new Report Grouping (This is the basic Building Block of the Report before you start rendering) * @constructor * @alias ReportGroup * @memberof Report * @param parent */ function ReportGroup(parent) { this._parent = parent; this._header = null; this._footer = null; this._detail = null; this._groupOnField = null; this._groupChecked = false; this._groupLastValue = null; this._child = null; this._hasRanHeader = false; this._runDetailAfterSubgroup = false; this._runHeaderWhen = Report.show.newPageOnly; this._lastData = {}; this._currentData = null; this._math = []; this._totals = {}; this._curBandWidth = []; this._curBandOffset = 0; this._level = -1; } /** * ReportDataSet * @class ReportDataSet * @desc This creates a Dataset Element for the Report * @param {ReportSection} parent - ReportSection element that is the parent of this object * @param {string?} parentDataKey - parent dataset data key * @constructor * @alias ReportDataSet * @memberOf Report * @return {ReportGroup} - Returns a auto-generated ReportGroup tied to this reportDataSet */ function ReportDataSet(parent, parentDataKey) { this._parent = parent; this._data = null; this._keys = null; this._dataType = dataTypes.NORMAL; if (parentDataKey) { this._dataType = dataTypes.PARENT; // noinspection JSUnusedGlobalSymbols this._parentDataKey = parentDataKey; } // noinspection JSUnusedGlobalSymbols this._recordCountCallback = null; this._child = new ReportGroup(this); if (this._parent && this._parent._parent === null) { this._child.header = this._child.pageHeader; this._child.footer = this._child.pageFooter; } this._totalFormatter = (data, callback) => { callback(null, data); }; return (this._child); } /* * This can be used as an a example method that is a paged data object. * This is a linked to internal Kellpro data and functions; * but you can base your own page-able data object off of it (see prototype) * @private **/ function ScopedDataObject(data, scope, formattingState) { this._scope = scope; this._data = data; this._dataType = dataTypes.NORMAL; this._formatters = null; this._result = null; if (formattingState !== null && formattingState !== undefined) { this._formattingState = formattingState; } else { this._formattingState = 0; } if (data._isQuery || data._isquery || typeof data === "string") { this._dataType = dataTypes.FUNCTIONAL; } else if (data.isRows) { this._dataType = dataTypes.PAGEABLE; this.isPaged = true; } else { if (this.error) { this.error(scope, null, 'warn', "Unknown scoped data type: " + Object.prototype.toString.apply(data)); } else { error("Unknown data type: ", Object.prototype.toString.apply(data), data); } } } /** * Report * @class Report * @desc Primary Report Creation Class * @param {(string|object|Report)} [parent] - Either the string name of the report to output to disk, "buffer" to output a buffer or a [Report, Group, or Section] that this is to be a child report of. * @param {object} [options] - default options for this report; landscape, paper, font, fontSize, autoPrint, fullScreen, negativeParentheses, autoCreate * @returns {ReportGroup|Report} - Normally returns a ReportGroup, or it can return itself if options.autoCreate is set to false */ function Report(parent, options) { // jshint ignore:line options = options || {}; this._reportName = "report.pdf"; this._outputType = Report.renderType.file; this._runHeaderWhen = Report.show.always; if (arguments.length) { if (typeof parent === "string" || typeof parent === "number") { this._parent = null; if (parent.toString() === "buffer") { this._outputType = Report.renderType.buffer; } else { this._reportName = parent.toString(); } } else if (typeof parent === "object" && typeof parent.write === "function" && typeof parent.end === "function") { this._parent = null; this._outputType = Report.renderType.pipe; this._pipe = parent; } else { if (parent == null) { this._parent = null; } else if (parent._isReport) { if (parent._child === null) { parent._child = this; this._parent = parent; } else if (parent._child._isSection) { parent._child.addReport(this); this._parent = parent._child; } else { Report.error("REPORTAPI: Report was passed an invalid parent; resetting parent to none"); this._parent = null; } } else if (parent._isSection || parent._isGroup) { if (options.isSibling === true) { let parentReport = parent; while (!parentReport._isReport) { parentReport = parentReport._parent; } parentReport._child.addReport(this); this._parent = parentReport; } else { parent.addReport(this); this._parent = parent; } } else { Report.error("REPORTAPI: Report was passed an invalid parent; resetting parent to none."); this._parent = null; } } } else { this._parent = null; } this._reportMode = reportRenderingMode.UNDEFINED; this._theader = null; this._tfooter = null; this._header = null; this._footer = null; this._userdata = null; this._curBandWidth = []; this._curBandOffset = 0; this._state = {}; this._landscape = options.landscape || false; this._paper = options.paper || "letter"; this._font = options.font || "Helvetica"; this._fontSize = options.fontSize || options.fontsize || 12; this._margins = options.margins || 72; this._autoPrint = options.autoPrint || options.autoprint || false; this._fullScreen = options.fullScreen || options.fullscreen || false; this._negativeParentheses = options.negativeParentheses || false; this._registeredFonts = {}; this._fonts = clone(Report._indexedFonts); this._info = options.info || {}; // We want to return a fully developed simple report (Report->Section->DataSet->Group) so we create it and then return the Group Object if (options.autocreate === false || options.autoCreate === false) { // TODO: This path might need to be deleted/modified; it doesn't setup _child or _detailGroup which will break code later in the code base. this._child = null; return this; } else { this._child = new ReportSection(this); this._detailGroup = this._child.addDataSet(); return (this._detailGroup); } } Report.prototype = /** @lends Report */ { _isReport: true, /** * is this the Root Report * @desc Returns if this is the primary root report of the entire report set * @returns {boolean} */ isRootReport: function () { return (this._parent === null); }, /** * toggle pdf fullScreen * @desc Attempts to make the report full screen when enabled * @param value {boolean} - true to try and force the screen full size * @returns {*} */ fullScreen: function(value) { if (arguments.length) { this._fullScreen = value; return this; } return this._fullScreen; }, /** * Toggle auto print on open * @param {boolean} value - true to enable * @returns {*} */ autoPrint: function (value) { if (arguments.length) { this._autoPrint = value; return this; } return this._autoPrint; }, /** * Enables negative numbers to be autowrapped in (parans) * @param {boolean} value - true to enable * @returns {*} */ negativeParentheses: function(value) { if (arguments.length) { this._negativeParentheses = value; return this; } return this._negativeParentheses; }, /** * set the output Type * @param type {Report.renderType} - Type of output * @param to - Pipe or Filename */ outputType: function(type, to) { if (arguments.length === 0) { return this._outputType; } if (typeof type === 'string') { if (type.toLowerCase() === 'buffer') { this._outputType = Report.renderType.buffer; } else { this._outputType = Report.renderType.file; this._reportName = type; } return this; } if (typeof type === 'object' && typeof type.write === 'function' && typeof type.end === 'function') { this._outputType = Report.renderType.pipe; this._pipe = type; return this; } if (type === Report.renderType.pipe) { this._outputType = Report.renderType.pipe; if (to) { this._pipe = to; } } else if (type === Report.renderType.buffer) { this._outputType = Report.renderType.buffer; } else if (type === Report.renderType.file) { this._outputType = Report.renderType.file; } else { this._outputType = Report.renderType.file; } return this; }, /** * Start the Rendering process * @param {function} callback - the callback to call when completed * @returns {*} */ render: function (callback) { if (this.isRootReport()) { return new Promise((resolve, reject) => { this._state = { isTitle: false, isFinal: false, headerSize: 0, footerSize: 0, additionalHeaderSize: 0, isCalc: false, cancelled: false, resetGroups: true, startX: 0, startY: 0, currentX: 0, currentY: 0, priorStart: [], parentData: {}, primaryData: null, // report: this, currentGroup: null, reportRenderMode: this._reportRenderMode() }; this._info.Producer = "fluentReports 1.00"; if (Report.trace) { console.error("Starting Tracing on Report to a ", this._outputType === Report.renderType.buffer ? "Buffer" : this._outputType === Report.renderType.pipe ? "Pipe" : "File " + this._reportName); if (Report.callbackDebugging) { console.error(" - Render callback is ", callback && typeof callback === "function" ? "valid" : "invalid"); } } // These get passed into the two page Wrappers for Page building information const pageDefaults = { paper: this._paper, landscape: this._landscape, margins: this._margins, fonts: this._fonts, registeredFonts: this._registeredFonts, info: this._info }; // Set the rendering mode if no functions are defined if (this._reportRenderMode() === reportRenderingMode.UNDEFINED) { this._reportRenderMode(reportRenderingMode.ASYNC); } // Find out Sizes of all the Headers/Footers let testit = new ReportRenderer(this, pageDefaults); testit._reportRenderMode = this._reportRenderMode(); testit.font(this._font, this._fontSize); testit.saveState(); // Catch the Printing so that we can see if we can track the "offset" of the Footer in case the footer // is moved to a literal Y position (without it being based on the prior Y position) let oPrint = testit.print; let oBand = testit.band; let oAddPage = testit._addPage; let onewLine = testit.newLine; // We are eliminating the height restriction for our sizing tests testit._height = 90000; // This needs to remain a "function" as "this" needs to point to the "testit" instance... testit._addPage = function () { oAddPage.call(this); this._height = 90000; }; // This needs to remain a "function" as "this" needs to point to the "testit" instance... testit.newLine = function (lines, callback) { this._firstMoveState = true; onewLine.call(this, lines, callback); }; // This needs to remain a "function" as "this" needs to point to the "testit" instance... testit.checkY = function (opt) { if (opt == null) { return; } let cY, y; y = cY = this.getCurrentY(); if (opt.y) { y = opt.y; } if (opt.addy) { y += opt.addy; } if (opt.addY) { y += opt.addY; } if (y > cY + (this._reportHeight / 3)) { // Did our move - move us over a 1/3 of the page down? If so then, it is something we need to track. if (!this._firstMoveState && !this._savedFirstMove) { this._savedFirstMove = y; } else if (this._firstMoveState && y < this._savedFirstMove) { // You never know, a user might do a print: y = 700; then a band: y: 680. So we actually want to save the 680 as the smallest coord. this._savedFirstMove = y; } else if (!this._savedFirstMove) { opt.addY = 0; opt.y = 0; Report.error("REPORTAPI: Your footer starts with printing some text, then uses an absolute move of greater than a third of the page. Please move first, then print!"); } } this._firstMoveState = true; //return y > cY + (this._reportHeight / 3); }; testit.band = function (data, options, callback) { this.checkY(options); oBand.call(this, data, options, callback); }; testit.print = function (data, options, callback) { this.checkY(options); oPrint.call(this, data, options, callback); }; testit.setCurrentY = function (y) { this.checkY({y: y}); ReportRenderer.prototype.setCurrentY.call(this, y); }; // Start the Calculation for the Test Report -> Then run the actual report. this._calculateFixedSizes(testit, "", () => { // Eliminate the testit code so it can be garbage collected. testit = null; oPrint = null; oBand = null; oAddPage = null; if (this._footer !== null) { this._state.footerSize = this._footer._partHeight; } if (this._header !== null) { this._state.headerSize = this._header._partHeight; } if (Report.trace) { console.error("Generating real report", this._reportName); } // ---------------------------------- // Lets Run the Real Report Header // ---------------------------------- const renderedReport = new ReportRenderer(this, pageDefaults); renderedReport._reportRenderMode = this._reportRenderMode(); renderedReport.font(this._font, this._fontSize); renderedReport.saveState(); //noinspection JSAccessibilityCheck renderedReport._setAutoPrint(this._autoPrint); renderedReport._setFullScreen(this._fullScreen); renderedReport.setNegativeParentheses(this._negativeParentheses); const primaryDataSet = this._detailGroup._findParentDataSet(); if (primaryDataSet && (primaryDataSet._dataType === dataTypes.NORMAL || primaryDataSet._dataType === dataTypes.PLAINOLDDATA)) { this._state.primaryData = primaryDataSet._data; } this._renderIt(renderedReport, this._state, null, () => { if (Report.trace) { console.error("Report Writing to ", this._outputType === Report.renderType.buffer ? "Buffer" : this._outputType === Report.renderType.pipe ? "Pipe" : "File " + this._reportName); } if (this._state.cancelled) { if (callback) { callback(null, false); } resolve(false); return; } renderedReport._finishPageNumbers(); switch (this._outputType) { case Report.renderType.pipe: //noinspection JSAccessibilityCheck renderedReport._pipe(this._pipe, (err) => { if (callback) { callback(err, this._pipe); } if (err) { reject(err); } else { resolve(this._pipe); } }); break; case Report.renderType.buffer: //noinspection JSAccessibilityCheck renderedReport._output( (data) => { if (callback) { callback(null, data); } resolve(data); }); break; default: //noinspection JSAccessibilityCheck renderedReport._write(this._reportName, (err) => { if (callback) { callback(err, this._reportName); } if (err) { reject(err); } else { resolve(this._reportName); } }); break; } }); }); //return (this._reportName); }); } else { return this._parent.render(callback); } }, /** * Add your own user data to be passed around in the report * @param value * @returns {*} */ userData: function (value) { if (arguments.length) { this._userdata = value; return this; } return this._userdata; }, /** * The current state of the report engine * @param value * @returns {object} */ state: function (value) { if (arguments.length) { this._state = value; } return this._state; }, /** * Set the paper size in pixels * @param {number} value * @returns {number} */ paper: function (value) { if (arguments.length) { this._paper = value; } return this._paper; }, /** * Set the paper into Landscape mode * @param value - True = Landscape, False = Portrait * @returns {boolean} */ landscape: function (value) { if (arguments.length) { this._landscape = value; } return this._landscape; }, font: function (value) { if (arguments.length) { this._font = value; } return this._font; }, /** * Set or Get the current font size * @param {number} [value] - set fontSize if this value is set * @returns {number} - the Font Size */ fontSize: function (value) { if (arguments.length) { this._fontSize = value; } return this._fontSize; }, fontBold: function () { // TODO: See if this function even needs to exist; it may be obsolete now // TODO: See if this works properly for added external fonts // See: fontBold in the renderer for changes we might have to do... const font = this._fonts[this._font]; switch (this._font) { case font.italic: case font.bolditalic: if (font.bolditalic) { this._font = font.bolditalic; } else if (font.bold) { this._font = font.bold; } break; default: if (font.bold) { this._font = font.bold; } break; } }, fontItalic: function () { const font = this._fonts[this._font]; switch (this._font) { case font.bold: case font.bolditalic: if (font.bolditalic) { this._font = font.bolditalic; } else if (font.italic) { this._font = font.italic; } break; default: if (font.italic) { this._font = font.italic; } break; } }, fontNormal: function () { const font = this._fonts[this._font]; if (font.normal) { this._font = font.normal; } }, margins: function (value) { if (arguments.length) { this._margins = value; } return this._margins; }, info: function(info) { if (arguments.length) { this._info = info; } return this._info; }, registerFont:function(name, definition){ if (this._state.hasOwnProperty("isTitle")) { Report.error("REPORTAPI: You cannot register a font while the report is running."); return; } if (definition.normal || definition.bold || definition.bolditalic || definition.italic) { this._registeredFonts[name] = definition; // Register in our structure so we can easily switch between Bold/Normal/Italic/etc this._fonts[name] = definition; for (let key in definition) { if (definition.hasOwnProperty(key)) { this._fonts[definition[key]] = definition; } } } else { this._fonts[name] = this._registeredFonts[name] = {normal: definition}; } }, // -------------------------------------- // Internal Private Variables & Functions // -------------------------------------- /** * Calculates a header/footer part of the report * @param part * @param Rpt * @param callback * @private */ _calculatePart: function(part, Rpt, callback) { if (part) { Rpt._addPage(); part.run(Rpt, {isCalc: true}, null, callback); } else { // No "if" check verification on "callback" because _calculatePart MUST have a callback callback(); } }, _calculateFixedSizes: function (Rpt, BogusData, callback) { this._calculatePart(this._header, Rpt, () => { this._calculatePart(this._tfooter, Rpt, () => { this._calculatePart(this._footer, Rpt, () => { this._child._calculateFixedSizes(Rpt, BogusData, callback); }); }); }); }, _pageHeader: function (value, settings) { if (this._header === null) { this._header = new ReportHeaderFooter(true); } if (arguments.length) { this._header.set(value, settings); } return (this._header.get()); }, _pageFooter: function (value, settings) { if (this._footer === null) { this._footer = new ReportHeaderFooter(false, true); } if (arguments.length) { this._footer.set(value, settings); } return (this._footer.get()); }, /*** * Sets the Title Header * @param value {string | function} * @param settings * @return {string | function} * @private */ _titleHeader: function (value, settings) { if (this._theader === null) { this._theader = new ReportHeaderFooter(true); } if (arguments.length) { this._theader.set(value, settings); } return (this._theader.get()); }, _finalSummary: function (value, settings) { if (this._tfooter === null) { this._tfooter = new ReportHeaderFooter(false, true); } if (arguments.length) { this._tfooter.set(value, settings); } return (this._tfooter.get()); }, _renderFinalFooter: function(Rpt, State, currentData, callback) { // Run final Footer! const dataSet = this._detailGroup._findParentDataSet(); dataSet._totalFormatter(this._detailGroup._totals, (err, data) => { Rpt.totals = data; Rpt._bandWidth(this._curBandWidth); Rpt._bandOf