Home / API

Show quantities on your drawings

Every item of the takeoff comes with the page it is on and its points on that page. That is enough to draw the run over your own rendering of the plans, highlight the run when someone picks a line in your quantity grid, and let an estimator check every foot against the drawing.

Three ways, depending on where you draw:

If you only need a finished picture, GET /v1/jobs/{id}/markup downloads the marked-up drawings InsulEngine makes, with every page of the set (see Downloads).

Find the page

Draw on the same PDF you uploaded. Each page of the takeoff names its file (drawing) and its page number in that file (page, 1 first), so with several PDFs, look up the file first, then the page. sheet_number is the sheet number printed in the title block (P1, M-201), for labels.

In the browser, with PDF.js

The trick is the SVG's viewBox: set it to the page's width and height, and the takeoff's points go in as they come, with no scaling, however large the page is drawn. This function makes the overlay; it has no dependencies:

// takeoff-overlay.js: one <svg> to lay over a page drawn at any size. Its viewBox is the page in PDF
// points, so the takeoff's points go in unchanged.
const COLORS = { CW: "#2f7de1", HW: "#d4451b", HWR: "#e08a1b", TW: "#b04fd6", STORM: "#189e77" };

const escape = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

export function takeoffOverlay(page, colors = COLORS) {
  const shapes = page.items.filter((item) => item.points && item.points.length).map((item) => {
    const color = colors[item.service] || "#5b7cff";
    const faded = item.state === "excluded" ? ' stroke-dasharray="12 8" opacity="0.5"' : "";
    const label = [item.size, item.service, item.quantity, item.unit].filter((v) => v != null).join(" ");
    const common = `data-id="${escape(item.id)}" fill="none" stroke="${color}" pointer-events="visibleStroke"${faded}`;
    if (item.points.length === 1) {
      const [x, y] = item.points[0];
      return `<circle ${common} cx="${x}" cy="${y}" r="8" stroke-width="3"><title>${escape(label)}</title></circle>`;
    }
    const points = item.points.map(([x, y]) => `${x},${y}`).join(" ");
    return `<polyline ${common} points="${points}" stroke-width="4" stroke-linecap="round" ` +
      `stroke-linejoin="round"><title>${escape(label)}</title></polyline>`;
  });
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${page.width} ${page.height}" ` +
    `style="position:absolute;inset:0;width:100%;height:100%;pointer-events:none">${shapes.join("")}</svg>`;
}

Then render the page with PDF.js (the pdfjs-dist package, version 4 or later) and lay the overlay on top. PDF.js applies the page's rotation as a viewer does, which is the orientation the takeoff's points use.

import * as pdfjsLib from "pdfjs-dist";
import { takeoffOverlay } from "./takeoff-overlay.js";

pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.min.mjs";   // copied from pdfjs-dist/build

// Draw one page of the drawings into `holder` (an empty <div>) with the takeoff over it. `page` is one
// entry of the takeoff's "pages"; `pdfUrl` is the PDF it names in "drawing", served by your own app.
export async function showPage(holder, pdfUrl, page, pixelsWide = 1600) {
  const pdf = await pdfjsLib.getDocument(pdfUrl).promise;
  const sheet = await pdf.getPage(page.page);
  const viewport = sheet.getViewport({ scale: pixelsWide / page.width });
  const canvas = document.createElement("canvas");
  canvas.width = Math.round(viewport.width);
  canvas.height = Math.round(viewport.height);
  canvas.style.cssText = "display:block;width:100%;height:auto";
  await sheet.render({ canvasContext: canvas.getContext("2d"), viewport }).promise;

  holder.style.position = "relative";
  holder.replaceChildren(canvas);
  holder.insertAdjacentHTML("beforeend", takeoffOverlay(page));

  // Clicking a line tells the rest of your page which item it is.
  holder.querySelector("svg").addEventListener("click", (event) => {
    const item = page.items.find((i) => i.id === event.target.dataset.id);
    if (item) holder.dispatchEvent(new CustomEvent("takeoff-item", { detail: item, bubbles: true }));
  });
}

To light up a run when someone picks its row in your grid, find the shape by its id and thicken it:

holder.querySelector(`[data-id="${CSS.escape(item.id)}"]`).setAttribute("stroke-width", "10");

Your browser code should load the takeoff from your own server, not from InsulEngine: keep the API key on the server (see Keep it safe).

On a server, on a page image

If you already render pages to images, scale each point by the image's width over the page's width. With Pillow:

from PIL import Image, ImageDraw

def draw_items(image_path, page, out_path):
    image = Image.open(image_path).convert("RGB")
    scale = image.width / page["width"]
    pen = ImageDraw.Draw(image)
    for item in page["items"]:
        points = [(x * scale, y * scale) for x, y in item.get("points") or []]
        if len(points) >= 2:
            pen.line(points, fill=(212, 69, 27), width=max(2, int(3 * scale)))
        elif points:
            x, y = points[0]
            pen.ellipse((x - 6, y - 6, x + 6, y + 6), outline=(212, 69, 27), width=2)
    image.save(out_path)

In the PDF, as annotations

pdf_points are the same places in the PDF's own coordinates (from the bottom-left of the page, before rotation): what a PDF annotation needs. This writes each run into a copy of the drawings as a polyline annotation that names its size, system and length, so it shows in any PDF viewer and can be hidden there:

from pypdf import PdfReader, PdfWriter
from pypdf.annotations import PolyLine
from pypdf.generic import ArrayObject, FloatObject, NameObject, TextStringObject

def annotate(pdf_path, takeoff, out_path):
    """A copy of one drawing PDF with every takeoff run on it as a PDF annotation."""
    writer = PdfWriter(clone_from=PdfReader(pdf_path))
    name = pdf_path.replace("\\", "/").rsplit("/", 1)[-1]
    for page in takeoff["pages"]:
        if page["drawing"] != name:
            continue
        for item in page["items"]:
            vertices = [tuple(p) for p in item.get("pdf_points") or []]
            if len(vertices) < 2:
                continue
            note = PolyLine(vertices=vertices)
            note[NameObject("/C")] = ArrayObject([FloatObject(0.83), FloatObject(0.27), FloatObject(0.11)])
            note[NameObject("/Contents")] = TextStringObject(
                f'{item["size"]} {item["service"]} {item["quantity"]} {item["unit"]}')
            writer.add_annotation(page_number=page["page"] - 1, annotation=note)
    with open(out_path, "wb") as out:
        writer.write(out)

What to draw