Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/OpenSign/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"dev": "vite",
"qa:local": "vite --mode local-qa --host 127.0.0.1 --port 3000",
"preview": "vite preview",
"test": "vitest run",
"start": "node server.cjs",
"version": "curl -s https://api.github.com/repos/opensignlabs/opensign/releases/latest | grep '\"tag_name\":' | awk -F '\"' '{print $4}' > ./public/version.txt",
"version-win": "powershell -Command \"Invoke-RestMethod -Uri 'https://api.github.com/repos/opensignlabs/opensign/releases/latest' | Select-Object -ExpandProperty tag_name | Out-File -FilePath ./public/version.txt\"",
Expand Down
2 changes: 2 additions & 0 deletions apps/OpenSign/src/constant/Utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios from "axios";
import { getErrorMessage, isCreditQuotaError } from "../utils/creditErrors";
import { copyPdfMetadata } from "../utils/pdfDocumentUtils";
import moment from "moment";
import {
PDFDocument,
Expand Down Expand Up @@ -3689,6 +3690,7 @@ export const reorderPdfPages = async (pdfArrayBuffer, orderArr) => {
orderArr.map((n) => n - 1)
);
pages.forEach((p) => newPdf.addPage(p));
copyPdfMetadata(pdfDoc, newPdf);
const pdfBase64 = await newPdf.saveAsBase64({ useObjectStreams: false });
const arrayBuffer = base64ToArrayBuffer(pdfBase64);
return { arrayBuffer, base64: pdfBase64, totalPages: orderArr.length };
Expand Down
8 changes: 2 additions & 6 deletions apps/OpenSign/src/pages/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
removeTrailingSegment
} from "../constant/Utils";
import { normalizeParseObjectResult } from "../utils/parseResult";
import { mergePdfBuffers } from "../utils/pdfDocumentUtils";
import { isCreditQuotaError } from "../utils/creditErrors";
import { PDFDocument } from "pdf-lib";
import axios from "axios";
Expand Down Expand Up @@ -315,12 +316,7 @@ const Forms = (props) => {
}

setfileload(true);
const merged = await PDFDocument.create();
for (const bytes of pdfBuffers) {
const doc = await PDFDocument.load(bytes, { ignoreEncryption: true });
const pages = await merged.copyPages(doc, doc.getPageIndices());
pages.forEach((p) => merged.addPage(p));
}
const merged = await mergePdfBuffers(pdfBuffers);

const pdfBytes = await merged.save({ useObjectStreams: false });
const name = generatePdfName(16);
Expand Down
40 changes: 40 additions & 0 deletions apps/OpenSign/src/utils/pdfDocumentUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { PDFDict, PDFDocument, PDFObjectCopier } from "pdf-lib";

/**
* Copies the document information dictionary (title, author, subject, keywords,
* custom entries, ...) to a document that was rebuilt with `copyPages`, which
* only carries over the pages.
* @param {PDFDocument} sourceDoc - document to read the metadata from
* @param {PDFDocument} targetDoc - document created with `PDFDocument.create()`
*/
export const copyPdfMetadata = (sourceDoc, targetDoc) => {
// Strings in the information dictionary of an encrypted document are ciphertext.
if (sourceDoc.isEncrypted) return;
const { context: source } = sourceDoc;
const { context: target } = targetDoc;
const sourceInfo = source.lookup(source.trailerInfo.Info);
if (!(sourceInfo instanceof PDFDict)) return;
const targetInfo = target.lookup(target.trailerInfo.Info, PDFDict);
const copier = PDFObjectCopier.for(source, target);
for (const [key, value] of sourceInfo.entries()) {
targetInfo.set(key, copier.copy(value));
}
};

/**
* Merges PDF files into one document that keeps the metadata of the first file.
* @param {(ArrayBuffer | Uint8Array)[]} pdfBuffers - PDF files in merge order
* @returns {Promise<PDFDocument>} merged document
*/
export const mergePdfBuffers = async (pdfBuffers) => {
const merged = await PDFDocument.create();
for (const [index, bytes] of pdfBuffers.entries()) {
const doc = await PDFDocument.load(bytes, { ignoreEncryption: true });
const pages = await merged.copyPages(doc, doc.getPageIndices());
pages.forEach((p) => merged.addPage(p));
if (index === 0) {
copyPdfMetadata(doc, merged);
}
}
return merged;
};
135 changes: 135 additions & 0 deletions apps/OpenSign/src/utils/pdfDocumentUtils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { PDFDict, PDFDocument, PDFName, PDFRef, PDFString } from "pdf-lib";
import { copyPdfMetadata, mergePdfBuffers } from "./pdfDocumentUtils";
import { reorderPdfPages } from "../constant/Utils";

const creationDate = new Date("2020-02-03T04:05:06Z");

const createPdf = async ({ pageCount = 1, metadata = true } = {}) => {
const doc = await PDFDocument.create();
for (let i = 0; i < pageCount; i++) {
doc.addPage();
}
if (metadata) {
doc.setTitle("Master service agreement");
doc.setAuthor("José García");
doc.setSubject("Contract");
doc.setKeywords(["invoice:42", "契約"]);
doc.setCreator("Word");
doc.setCreationDate(creationDate);
}
return doc;
};

const expectOriginalMetadata = (doc) => {
expect(doc.getTitle()).toBe("Master service agreement");
expect(doc.getAuthor()).toBe("José García");
expect(doc.getSubject()).toBe("Contract");
expect(doc.getKeywords()).toBe("invoice:42 契約");
expect(doc.getCreator()).toBe("Word");
expect(doc.getCreationDate()).toEqual(creationDate);
};

const reload = async (doc) =>
PDFDocument.load(await doc.save({ useObjectStreams: false }), {
updateMetadata: false
});

const infoDict = (doc) =>
doc.context.lookup(doc.context.trailerInfo.Info, PDFDict);

describe("mergePdfBuffers", () => {
it("keeps the metadata of a single uploaded PDF", async () => {
const pdf = await (await createPdf()).save();

expectOriginalMetadata(await reload(await mergePdfBuffers([pdf])));
});

it("keeps the metadata of the first PDF and all pages when merging", async () => {
const first = await (await createPdf({ pageCount: 2 })).save();
const second = await createPdf();
second.setTitle("Second file");
second.setKeywords(["second"]);

const merged = await reload(
await mergePdfBuffers([first, await second.save()])
);

expect(merged.getPageCount()).toBe(3);
expectOriginalMetadata(merged);
});

it("keeps custom entries of the information dictionary", async () => {
const doc = await createPdf();
infoDict(doc).set(PDFName.of("Department"), PDFString.of("Legal"));

const merged = await reload(await mergePdfBuffers([await doc.save()]));

expect(infoDict(merged).lookup(PDFName.of("Department")).asString()).toBe(
"Legal"
);
});

it("merges PDFs that have no metadata", async () => {
const pdf = await (await createPdf({ metadata: false })).save();

const merged = await reload(await mergePdfBuffers([pdf, pdf]));

expect(merged.getPageCount()).toBe(2);
expect(merged.getKeywords()).toBeUndefined();
});
});

describe("copyPdfMetadata", () => {
it("copies metadata stored as indirect objects", async () => {
const source = await createPdf();
const titleRef = source.context.register(PDFString.of("Indirect title"));
infoDict(source).set(PDFName.of("Title"), titleRef);
const target = await PDFDocument.create();

copyPdfMetadata(source, target);

expect((await reload(target)).getTitle()).toBe("Indirect title");
});

it("still saves when an entry points to a missing object", async () => {
const source = await createPdf();
infoDict(source).set(PDFName.of("Broken"), PDFRef.of(9999));
const target = await PDFDocument.create();

copyPdfMetadata(source, target);

expect((await reload(target)).getTitle()).toBe("Master service agreement");
});

it("does not copy the ciphertext metadata of an encrypted PDF", async () => {
const source = await createPdf();
source.isEncrypted = true;
const target = await PDFDocument.create();

copyPdfMetadata(source, target);

expect(target.getKeywords()).toBeUndefined();
});
});

describe("reorderPdfPages", () => {
it("keeps the metadata and applies the new page order", async () => {
const doc = await createPdf({ pageCount: 2 });
doc.getPage(0).setWidth(100);
doc.getPage(1).setWidth(200);

const { arrayBuffer, totalPages } = await reorderPdfPages(
await doc.save(),
[2, 1]
);

const reordered = await PDFDocument.load(arrayBuffer, {
updateMetadata: false
});
expect(totalPages).toBe(2);
expect(reordered.getPage(0).getWidth()).toBe(200);
expectOriginalMetadata(reordered);
});
});