const baseUrl = 'http://localhost:8765';
// GET /version
async function getVersion() {
try {
const res = await fetch(`${baseUrl}/version`);
const json = await res.json();
console.log("Version:", json.Version);
} catch (error) {
console.error("Error getting version:", error);
}
}
// GET /defaultprinter
async function getDefaultPrinter() {
try {
const res = await fetch(`${baseUrl}/defaultprinter`);
const json = await res.json();
return json.defaultPrinter;
} catch (error) {
console.error("Error getting default printer:", error);
return null;
}
}
// GET /printers
async function getPrinters() {
try {
const res = await fetch(`${baseUrl}/printers`);
const json = await res.json();
console.log("Installed Printers:", json);
} catch (error) {
console.error("Error getting printers:", error);
}
}
// GET /history
async function getPrintHistory() {
try {
const res = await fetch(`${baseUrl}/history`);
const json = await res.json();
console.log("Print History:", json);
} catch (error) {
console.error("Error getting print history:", error);
}
}
// POST /print
async function printPdf(base64Pdf, printerName, userId) {
try {
const res = await fetch(`${baseUrl}/print`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pdfBase64: base64Pdf,
printerName: printerName,
userId: userId
})
});
const text = await res.text();
console.log("Print Response:", text);
} catch (error) {
console.error("Error printing PDF:", error);
}
}
// Utility: fetch a PDF and convert to base64
async function loadPdfAsBase64(url) {
try {
const res = await fetch(url);
const blob = await res.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.onerror = () => reject("Failed to convert PDF to base64");
reader.readAsDataURL(blob);
});
} catch (error) {
console.error("Error loading PDF:", error);
return null;
}
}
// GET /quit
async function quitAgent() {
try {
const res = await fetch(`${baseUrl}/quit`);
const text = await res.text();
console.log("Quit Response:", text);
} catch (error) {
console.error("Error quitting agent:", error);
}
}
// ✅ Example Usage
(async () => {
await getVersion();
const defaultPrinter = await getDefaultPrinter();
if (!defaultPrinter) {
console.error("No default printer found. Aborting print.");
return;
}
await getPrinters();
await getPrintHistory();
const pdfBase64 = await loadPdfAsBase64('/sample.pdf'); // Adjust to valid PDF path
if (!pdfBase64) {
console.error("Failed to load PDF for printing.");
return;
}
await printPdf(pdfBase64, defaultPrinter, 'DemoUser');
// await quitAgent(); // Uncomment to stop agent
})();