MCPcopy Create free account
hub / github.com/LibPDF-js/core / main

Function main

examples/03-forms/fill-text-fields.ts:13–110  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

11import { formatBytes, loadFixture, saveOutput } from "../utils";
12
13async function main() {
14 console.log("Filling text fields in a PDF form...\n");
15
16 // Load a PDF with form fields
17 const bytes = await loadFixture("forms", "fancy_fields.pdf");
18 const pdf = await PDF.load(bytes);
19
20 // Get the form
21 const form = pdf.getForm();
22 if (!form) {
23 console.log("This PDF does not contain a form.");
24 return;
25 }
26
27 // List all text fields
28 const textFields = form.getTextFields();
29 console.log("=== Available Text Fields ===");
30 for (const field of textFields) {
31 console.log(` - "${field.name}" (current: "${field.getValue() || "(empty)"}")`);
32 }
33 console.log("");
34
35 // Fill text fields by name
36 console.log("=== Filling Text Fields ===");
37
38 for (const field of textFields) {
39 // Get the field by name
40 const textField = form.getTextField(field.name);
41 if (!textField) {
42 continue;
43 }
44
45 // Skip read-only fields
46 if (field.isReadOnly()) {
47 console.log(`Skipping "${field.name}" - read-only`);
48 continue;
49 }
50
51 // Generate a sample value based on field name
52 let value: string;
53 const nameLower = field.name.toLowerCase();
54
55 if (nameLower.includes("name")) {
56 value = "John Doe";
57 } else if (nameLower.includes("email")) {
58 value = "john.doe@example.com";
59 } else if (nameLower.includes("phone") || nameLower.includes("tel")) {
60 value = "(555) 123-4567";
61 } else if (nameLower.includes("address")) {
62 value = "123 Main Street";
63 } else if (nameLower.includes("city")) {
64 value = "Springfield";
65 } else if (nameLower.includes("state")) {
66 value = "IL";
67 } else if (nameLower.includes("zip") || nameLower.includes("postal")) {
68 value = "62701";
69 } else if (nameLower.includes("date")) {
70 value = new Date().toISOString().split("T")[0] ?? "";

Callers 1

Calls 10

loadFixtureFunction · 0.90
saveOutputFunction · 0.90
formatBytesFunction · 0.90
getFormMethod · 0.80
getTextFieldsMethod · 0.80
getTextFieldMethod · 0.80
saveMethod · 0.80
loadMethod · 0.45
getValueMethod · 0.45
setValueMethod · 0.45

Tested by

no test coverage detected