Jonathan Jenne 446bcfeb9e 20-09-2023
2023-09-20 13:42:24 +02:00

192 lines
6.5 KiB
TypeScript
Raw Blame History

import PSPDFKitType, { AnnotationsUnion } from "./index";
import { Instance, WidgetAnnotation, ToolbarItem } from "./index";
declare const PSPDFKit: typeof PSPDFKitType
const { List } = PSPDFKit.Immutable;
const { Rect } = PSPDFKit.Geometry;
const { SignatureFormField } = PSPDFKit.FormFields;
const { DRAW, TYPE } = PSPDFKit.ElectronicSignatureCreationMode;
const { DISABLED } = PSPDFKit.AutoSaveMode;
interface EnvelopeResponse {
receiverId: number;
envelope: Envelope;
}
interface Envelope {
id: number;
userId: number;
title: string;
contractType: number;
status: number;
uuid: string;
}
class Settings {
public static allowedToolbarItems: string[] = [
"sidebar-thumbnails",
"sidebar-document-ouline",
"sidebar-bookmarks",
"pager",
"pan",
"zoom-out",
"zoom-in",
"zoom-mode",
"spacer",
"search"
]
}
export class App {
public static Instance: Instance;
// This function will be called in the ShowEnvelope.razor page
// and will trigger loading of the Editor Interface
public static async loadPDFFromUrl (container: string, envelopeKey: string) {
console.debug("Loading PSPDFKit..");
const arrayBuffer = await App.loadDocument(`/api/download/${envelopeKey}`);
const envelopeObject: EnvelopeResponse = await App.loadData(`/api/get-data/${envelopeKey}`);
App.Instance = await App.loadPSPDFKit(arrayBuffer, container)
App.configurePSPDFKit(this.Instance)
console.debug(envelopeObject.envelope.id);
console.debug("PSPDFKit configured!");
const id = PSPDFKit.generateInstantId()
const annotation: WidgetAnnotation = App.createSignatureAnnotation(id, 150, 50, 50, 50, 0)
const formField = new SignatureFormField({
name: id,
annotationIds: List([annotation.id])
})
console.debug("Annotation created.")
const [createdAnnotation] = await App.Instance.create([annotation, formField])
console.debug(createdAnnotation)
}
// Makes a call to the supplied url and fetches the binary response as an array buffer
private static loadDocument(url: string): Promise<ArrayBuffer> {
return fetch(url, { credentials: "include" })
.then(res => res.arrayBuffer());
}
// Makes a call to the supplied url and fetches the json response as an object
private static loadData(url: string): Promise<any> {
return fetch(url, { credentials: "include" })
.then(res => res.json());
}
// Load the PSPDFKit UI by setting a target element as the container to render in
// and a arraybuffer which represents the document that should be displayed.
private static loadPSPDFKit(arrayBuffer: ArrayBuffer, container: string): Promise<Instance> {
const annotationPresets = PSPDFKit.defaultAnnotationPresets;
console.log(annotationPresets)
annotationPresets.ink = {
lineWidth: 10
};
return PSPDFKit.load({
container: container,
document: arrayBuffer,
autoSaveMode: DISABLED,
annotationPresets,
electronicSignatures: {
creationModes: [DRAW]
}
})
}
private static configurePSPDFKit(instance: Instance) {
instance.addEventListener("annotations.load", (loadedAnnotations) => {
console.log("annotations loaded", loadedAnnotations.toJS());
})
instance.addEventListener("annotations.change", () => {
console.log("annotations changed")
})
instance.addEventListener("annotations.create", (createdAnnotations) => {
const annotation: AnnotationsUnion = createdAnnotations[0];
console.log("annotations created", createdAnnotations.toJS());
})
const filteredItems: Array<ToolbarItem> = instance.toolbarItems
.filter((item) => Settings.allowedToolbarItems.includes(item.type))
const customItems: ToolbarItem[] = [
{
type: "custom",
id: "button-finish",
title: "Abschlie<69>en",
icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-check2-circle" viewBox="0 0 16 16">
<path d="M2.5 8a5.5 5.5 0 0 1 8.25-4.764.5.5 0 0 0 .5-.866A6.5 6.5 0 1 0 14.5 8a.5.5 0 0 0-1 0 5.5 5.5 0 1 1-11 0z"/>
<path d="M15.354 3.354a.5.5 0 0 0-.708-.708L8 9.293 5.354 6.646a.5.5 0 1 0-.708.708l3 3a.5.5 0 0 0 .708 0l7-7z" />
</svg>`,
onPress: this.handleFinish
}
]
instance.setToolbarItems(filteredItems.concat(customItems))
}
private static async handleFinish(event: any) {
await App.Instance.applyOperations([{ type: "flattenAnnotations" }])
//await downloadDocument();
}
private static async downloadDocument() {
const buffer = await App.Instance.exportPDF({ flatten: true });
const supportsDownloadAttribute = HTMLAnchorElement.prototype.hasOwnProperty("download");
const blob = new Blob([buffer], { type: "application/pdf" });
if (!supportsDownloadAttribute) {
const reader = new FileReader();
reader.onloadend = function () {
const dataUrl = reader.result;
downloadPdf(dataUrl);
};
reader.readAsDataURL(blob);
} else {
const objectUrl = window.URL.createObjectURL(blob);
downloadPdf(objectUrl);
window.URL.revokeObjectURL(objectUrl);
}
function downloadPdf(blob) {
const a = document.createElement("a");
a.href = blob;
a.style.display = "none";
a.download = "download.pdf";
a.setAttribute("download", "download.pdf");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
private static createSignatureAnnotation(id: string, x: number, y: number, top: number, left: number, pageIndex: number): WidgetAnnotation {
const annotation = new PSPDFKit.Annotations.WidgetAnnotation({
id: id,
pageIndex: pageIndex,
formFieldName: id,
boundingBox: new Rect({
width: x,
height: y,
top: top,
left: left
})
})
return annotation
}
}