Skip to content

Commit

Permalink
Clean up jsPDF override code
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcmyers committed Apr 20, 2021
1 parent 6f85788 commit 108a4f0
Showing 1 changed file with 24 additions and 23 deletions.
47 changes: 24 additions & 23 deletions constrain-pdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,46 +252,46 @@ function override_jsPDF(jspdf, ctx, figure) {
const prototype = jspdf.context2d.constructor.prototype,
Point = jspdf.internal.Point

// Allow recognizing special contexts
prototype.printMedia = true

// setLineDash() is not implemented by jsPDF.Context2d
prototype.setLineDash = function(pattern) {
this.ctx.lineDash = pattern
jspdf.setLineDashPattern(pattern.map(x => x * figure.scale))
}
// getLineDash() is not implemented by jsPDF.context2d
prototype.getLineDash = function() {
const r = this.ctx.lineDash
if (!r) return []
if (r.length % 2 == 0) return r
else return r.concat(r)
}
// Need to use original context to make text measurements correct
prototype.measureText = function(s) {
ctx.font = this.font
return ctx.measureText(s)
}
prototype.closePath = function() {
let pathBegin = new Point(0, 0);
let i = 0;
for (i = this.path.length - 1; i !== -1; i--) {
if (this.path[i].type === "begin") {
if (
typeof this.path[i + 1] === "object" &&
typeof this.path[i + 1].x === "number"
) {
pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);
this.path.push({
type: "lt",
x: pathBegin.x,
y: pathBegin.y
});
break;
// Remove extra path segment that Context2d.closePath() adds for
// some reason.
prototype.closePath = function() {
let pathBegin = new Point(0, 0)
for (let i = this.path.length - 1; i >= 0; i--) {
if (this.path[i].type === "begin") {
if (typeof this.path[i + 1] === "object" && typeof this.path[i + 1].x === "number") {
pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y)
this.path.push({
type: "lt",
x: pathBegin.x,
y: pathBegin.y
})
break
}
}
}
}
this.path.push({ type: "close" })
this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y)
}
this.path.push({
type: "close"
});
this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);
}
}

class PrintJob {
Expand All @@ -312,9 +312,10 @@ class PrintJob {
const figure = this.figure
const save_ctx = figure.ctx
const orientation = (figure.width > figure.height) ? "l" : "p"
const unit = "px"
const output = new jspdf.jsPDF({
orientation,
unit: "px",
unit,
format: [figure.width * figure.scale, figure.height * figure.scale],
hot_fixes: ["px_scaling"]
})
Expand Down

0 comments on commit 108a4f0

Please sign in to comment.