pdf3.js 2.82 KB
class PDF3 {

	"use strict";

	constructor() {
		/** Coordinate container that occupies the whole page **/
		this.A4 = new Div(
			new Vector(0, 0),
			new Vector(595, 842)
		);

		this.containerSize = 86;

		this.body = {
			"font": "times",
			"type": "normal",
			"size": 9
		};

		this.title = {
			"font": "times",
			"type": "bold",
			"size": 13
		};

		this.subtitle = {
			"font": "times",
			"type": "bold",
			"size": 8
		};

		this.line = () => new Line(
			new Vector(Pos.beg_margin, Pos.end),
			new Vector(Pos.end_margin, Pos.end)
		);
	}
	pdf(data) {
		let pointer = new Vector(0,0);

		pointer = this.header(pointer, data['header']);
		
		Object.keys(data['anomalies']).forEach( title =>
			pointer = this.table(
				pointer, title, data['anomalies'][title]
			)
		);
		
		return this.A4;
	}

	header(pointer, data) {

		const header = this.A4.addRelativeChild( new Div(pointer, new Vector(Pos.end, 10)) );

		header.addRelativeChildren([

			this.line(),
			
			new Text(
				"Informe para Taller de Mantenimiento",
				new Vector(Pos.middle, Pos.third),
				this.title,
				"center"
			),

			new Text(
				`Fecha: ${data['fecha']}`,
				new Vector(Pos.end_margin, Pos.two_thirds),
				this.body,
				"right"
			),

			new Text(
				[`Razon social: ${data['cp']} - ${data['rsocial']}`, `Patente: ${data['patente']}`],
				new Vector(Pos.beg_margin, Pos.two_thirds),
				this.body
			)
		])

		return pointer.addxy(0,10);
	}

	table(pointer, title, data) {

		const lines = this.makelines(data, 55);
		title = this.partition(title, 20)

		const table = this.A4.addRelativeChild( new Div(pointer.addxy(5,1), new Vector(90, 2 * (lines.length + 1))) );
		
		const left = table.addRelativeChild( new Div(new Vector(0,0), new Vector(30, 100)) );
		const right = table.addRelativeChild( new Div(new Vector(30,0), new Vector(70, 100)) );

		left.drawOutline = true;
		right.drawOutline = true;

		left.addRelativeChild(
			new Text(
				title,
				new Vector(Pos.middle, Pos.middle - (title.length - 1) * 1.1),
				this.subtitle,
				"center"
			)
		)

		let subpointer = right.position.addxy(186, 0.025 * this.A4.size.y);
		
		lines.forEach( text => {

			right.addAbsoluteChild(
				new Text(text, subpointer, this.body, "center")
			);

			subpointer = subpointer.addxy(0, 0.02 * this.A4.size.y);
		});

		return pointer.addxy(0, 2 * (lines.length + 1) + 1);
	}

	makelines(data, linesize) {
		/** merge all segment lists to make the actual lines that will be used **/
		return data.reduce( (lines, entry) =>
			lines.concat(
				this.partition(`${entry['description']} - ${entry['severity']}`, linesize)
			),
			[]
		);
	}

	/** slice in segments of 70 characters **/
	partition(string, linesize) {
		const result = [];

		let s = 0;
		while (string.slice(s, s + linesize) !== '') {
			result.push(string.slice(s, s + linesize));
			s += linesize;
		}

		return result;
	}
}