ScanPro API Client Guide
This guide provides detailed instructions on how to use the ScanPro API client to interact with ScanPro's document processing services.
Table of Contents
Installation
First, include the ScanPro API client in your Next.js project.
Option 1: Import the provided client class
Place the scanpro-client.ts file in your project's API utility folder, for example, src/api/scanpro-client.ts.
Option 2: Install via npm (if available)
npm install scanpro-api-client
Basic Setup
Import the client and create an instance:
import { ScanProApiClient } from "@/api/scanpro-client";
const scanproApi = new ScanProApiClient();
const scanproApi = new ScanProApiClient("https://scanpro.cc");
import scanproApi from "@/api/scanpro-client";
Authentication
The ScanPro API supports API key authentication for programmatic access.
scanproApi.setApiKey("sk_your_api_key_here");
scanproApi.clearApiKey();
File Conversion
Convert files between various formats.
Basic Conversion
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
const file = fileInput.files?.[0];
if (file) {
try {
const result = await scanproApi.convertFile(file, "docx");
console.log("File converted successfully");
console.log("Download URL:", result.fileUrl);
} catch (error) {
console.error("Conversion failed:", error);
}
}
Conversion with Options & Progress Tracking
const result = await scanproApi.convertFile(file, "docx", {
ocr: true,
quality: 90,
password: "secret",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
progressBar.value = progress;
},
});
Supported Formats
- Input: pdf, docx, xlsx, pptx, rtf, txt, html, jpg, jpeg, png
- Output: pdf, docx, xlsx, pptx, rtf, txt, html, jpg, jpeg, png
PDF Compression
Compress PDF files to reduce file size while maintaining quality.
const result = await scanproApi.compressPdf(pdfFile, {
quality: "medium",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Original size: ${result.originalSize} bytes`);
console.log(`Compressed size: ${result.compressedSize} bytes`);
console.log(`Compression ratio: ${result.compressionRatio}`);
Universal File Compression
Compress various file types including PDFs, images, and Office documents.
const result = await scanproApi.compressUniversal(file, {
quality: "medium",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Original size: ${result.originalSize} bytes`);
console.log(`Compressed size: ${result.compressedSize} bytes`);
console.log(`Compression ratio: ${result.compressionRatio}`);
PDF Merging
Combine multiple PDF files into a single document.
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
const files = Array.from(fileInput.files || []);
if (files.length >= 2) {
try {
const result = await scanproApi.mergePdfs(files, {
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Merged ${result.fileCount} files`);
console.log(`Total input size: ${result.totalInputSize} bytes`);
console.log(`Merged file size: ${result.mergedSize} bytes`);
console.log("Download URL:", result.fileUrl);
} catch (error) {
console.error("Merge failed:", error);
}
}
Merging with Custom Order
const result = await scanproApi.mergePdfs(files, {
order: [2, 0, 1],
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
PDF Splitting
Split a PDF document into multiple files.
Basic Splitting by Page Ranges
const result = await scanproApi.splitPdf(pdfFile, {
splitMethod: "range",
pageRanges: "1-3, 5, 7-9",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Created ${result.splitParts?.length} PDF parts`);
result.splitParts?.forEach((part, index) => {
console.log(`Part ${index + 1}: Pages ${part.pages.join(", ")}`);
console.log(`Download URL: ${part.fileUrl}`);
});
const result = await scanproApi.splitPdf(pdfFile, {
splitMethod: "extract",
});
Split Every N Pages
const result = await scanproApi.splitPdf(pdfFile, {
splitMethod: "every",
everyNPages: 2,
});
Handling Large PDF Splitting Jobs
For large PDFs, the splitting process is asynchronous and requires checking the status:
const initialResult = await scanproApi.splitPdf(largePdfFile);
if (
initialResult.isLargeJob &&
initialResult.jobId &&
initialResult.statusUrl
) {
console.log("Large job started, monitoring progress...");
const checkStatus = async () => {
const statusResult = await scanproApi.getSplitStatus(initialResult.jobId!);
console.log(`Progress: ${statusResult.progress}%`);
console.log(`Completed: ${statusResult.completed}/${statusResult.total}`);
if (statusResult.status === "completed") {
console.log("Job completed!");
console.log(`Created ${statusResult.results.length} PDF parts`);
statusResult.results.forEach((part, index) => {
console.log(`Part ${index + 1}: ${part.fileUrl}`);
});
} else if (statusResult.status === "error") {
console.error("Job failed:", statusResult.error);
} else {
setTimeout(checkStatus, 2000);
}
};
checkStatus();
}
PDF Page Rotation
Rotate pages in a PDF document.
const rotations = [
{ pageNumber: 1, angle: 90 },
{ pageNumber: 2, angle: 180 },
{ pageNumber: 3, angle: 270 },
];
const result = await scanproApi.rotatePdf(pdfFile, rotations, {
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Rotated ${result.rotatedPages} pages`);
console.log(`Download URL: ${result.fileUrl}`);
PDF Watermarking
Add text or image watermarks to PDF files.
Text Watermark
const result = await scanproApi.watermarkPdf(pdfFile, {
watermarkType: "text",
text: "CONFIDENTIAL",
textColor: "#FF0000",
fontSize: 48,
fontFamily: "Arial",
opacity: 30,
rotation: 45,
position: "center",
pages: "all",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Added watermark to ${result.pagesWatermarked} pages`);
console.log(`Download URL: ${result.fileUrl}`);
Image Watermark
const imageFile = imageInput.files?.[0];
if (pdfFile && imageFile) {
const result = await scanproApi.watermarkPdf(pdfFile, {
watermarkType: "image",
watermarkImage: imageFile,
scale: 50,
opacity: 30,
rotation: 0,
position: "bottom-right",
pages: "custom",
customPages: "1-5, 10",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
}
Custom Position Watermark
const result = await scanproApi.watermarkPdf(pdfFile, {
watermarkType: "text",
text: "DRAFT",
position: "custom",
customX: 25,
customY: 75,
});
PDF Protection & Security
Protect PDFs with passwords or unlock protected PDFs.
Check if a PDF is Password Protected
const checkResult = await scanproApi.checkPdfProtection(pdfFile);
if (checkResult.isPasswordProtected) {
console.log("This PDF is password protected");
} else {
console.log("This PDF is not password protected");
}
Protect a PDF with Password
const result = await scanproApi.protectPdf(pdfFile, "your_password", {
permission: "restricted",
allowPrinting: true,
allowCopying: false,
allowEditing: false,
protectionLevel: "256",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`PDF protected successfully`);
console.log(`Download URL: ${result.fileUrl}`);
Unlock a Protected PDF
const result = await scanproApi.unlockPdf(pdfFile, "pdf_password", {
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`PDF unlocked successfully using ${result.methodUsed}`);
console.log(`Download URL: ${result.fileUrl}`);
PDF Repair
Repair corrupted or damaged PDF files.
const result = await scanproApi.repairPdf(pdfFile, {
repairMode: "standard",
password: "pdf_password",
preserveFormFields: true,
preserveAnnotations: true,
preserveBookmarks: true,
optimizeImages: false,
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`PDF repaired successfully`);
console.log(`Issues fixed: ${result.details?.fixed.join(", ")}`);
console.log(`Warnings: ${result.details?.warnings.join(", ")}`);
console.log(`Original size: ${result.details?.originalSize} bytes`);
console.log(`New size: ${result.details?.newSize} bytes`);
console.log(`Download URL: ${result.fileUrl}`);
PDF Page Numbering
Add page numbers to a PDF document.
const result = await scanproApi.addPageNumbers(pdfFile, {
format: "numeric",
position: "bottom-center",
fontFamily: "Arial",
fontSize: 12,
color: "#000000",
startNumber: 1,
prefix: "Page ",
suffix: "",
marginX: 40,
marginY: 30,
selectedPages: "1-5",
skipFirstPage: true,
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Added page numbers to ${result.numberedPages} pages`);
console.log(`Download URL: ${result.fileUrl}`);
PDF Information
Get information about a PDF document.
const info = await scanproApi.getPdfInfo(pdfFile);
console.log(`File: ${info.filename}`);
console.log(`Size: ${info.fileSize} bytes`);
console.log(`Pages: ${info.pageCount}`);
console.log(
`Dimensions: ${info.dimensions.width} x ${info.dimensions.height} points`
);
PDF Editing
Process a PDF for editing and save edits.
Process PDF for Editing
const result = await scanproApi.processPdfForEditing(pdfFile, {
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Processed ${result.pageCount} pages for editing`);
const sessionId = result.sessionId;
const pages = result.pages;
pages.forEach((page, index) => {
console.log(`Page ${index + 1} image: ${page.imageUrl}`);
console.log(`Dimensions: ${page.width} x ${page.height}`);
});
Save Edited PDF
const editResult = await scanproApi.saveEditedPdf("original.pdf", pages);
console.log(`Edits saved successfully`);
console.log(`Download URL: ${editResult.fileUrl}`);
PDF Signing
Add signatures, stamps, and text elements to a PDF.
const processResult = await scanproApi.processPdfForEditing(pdfFile);
const signatureElements = [
{
id: "1",
type: "signature",
position: { x: 100, y: 500 },
size: { width: 200, height: 50 },
data: "data:image/png;base64,...",
rotation: 0,
scale: 1,
page: 0,
},
{
id: "2",
type: "text",
position: { x: 100, y: 550 },
size: { width: 200, height: 20 },
data: "John Doe, CEO",
rotation: 0,
scale: 1,
page: 0,
fontSize: 12,
fontFamily: "Arial",
color: "#000000",
},
{
id: "3",
type: "date",
position: { x: 100, y: 580 },
size: { width: 200, height: 20 },
data: "",
rotation: 0,
scale: 1,
page: 0,
fontSize: 12,
fontFamily: "Arial",
color: "#000000",
},
];
const signResult = await scanproApi.signPdf(
pdfFile,
signatureElements,
processResult.pages,
{
performOcr: true,
ocrLanguage: "eng",
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
}
);
console.log(`PDF signed successfully`);
console.log(`Signed PDF URL: ${signResult.fileUrl}`);
if (signResult.ocrComplete) {
console.log(`Searchable PDF URL: ${signResult.searchablePdfUrl}`);
}
PDF Chat
Chat with a PDF document using AI.
Initialize Chat Session
const chatResult = await scanproApi.initChatSession(pdfFile, {
onProgress: (progress) => {
console.log(`Upload progress: ${progress}%`);
},
});
console.log(`Chat session initialized`);
console.log(`Session ID: ${chatResult.sessionId}`);
console.log(`AI: ${chatResult.message}`);
const sessionId = chatResult.sessionId;
Send Messages and Get Responses
const messageResult = await scanproApi.sendChatMessage(
sessionId,
"What is the main topic of this document?"
);
console.log(`AI: ${messageResult.message}`);
const followUpResult = await scanproApi.sendChatMessage(
sessionId,
"Can you summarize the key points?"
);
console.log(`AI: ${followUpResult.message}`);
Get Chat History
const historyResult = await scanproApi.getChatHistory(sessionId);
console.log(`Chat started at: ${historyResult.createdAt}`);
console.log("Conversation:");
historyResult.messages.forEach((message) => {
console.log(`${message.role}: ${message.content}`);
console.log(`Time: ${message.timestamp}`);
});
End Chat Session
await scanproApi.deleteChatSession(sessionId);
console.log("Chat session deleted");
Managing API Keys
Generate, list, and revoke API keys for programmatic access.
Generate API Key
const keyResult = await scanproApi.generateApiKey(
"Development API Key",
["convert", "compress", "merge", "split"]
);
console.log(`API Key created: ${keyResult.key.name}`);
console.log(`Key value: ${keyResult.key.key}`);
console.log(`Permissions: ${keyResult.key.permissions.join(", ")}`);
List API Keys
const keysResult = await scanproApi.listApiKeys();
console.log(`You have ${keysResult.keys.length} API keys`);
keysResult.keys.forEach((key) => {
console.log(`ID: ${key.id}`);
console.log(`Name: ${key.name}`);
console.log(`Key: ${key.key}`);
console.log(`Permissions: ${key.permissions.join(", ")}`);
console.log(`Created: ${key.createdAt}`);
console.log(`Last used: ${key.lastUsed || "Never"}`);
console.log(`Expires: ${key.expiresAt || "Never"}`);
});
Revoke API Key
const revokeResult = await scanproApi.revokeApiKey("key_id_here");
if (revokeResult.success) {
console.log("API key revoked successfully");
}
Error Handling
Handle API errors gracefully.
try {
const result = await scanproApi.convertFile(file, "docx");
console.log("Success:", result);
} catch (error) {
if (error instanceof Error) {
console.error("API Error:", error.message);
errorElement.textContent = error.message;
errorElement.style.display = "block";
}
}
Complete Example: PDF Workflow Application
Here's a complete example of a simple PDF workflow application:
import { ScanProApiClient } from "@/api/scanpro-client";
const scanproApi = new ScanProApiClient();
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
const convertBtn = document.getElementById("convertBtn") as HTMLButtonElement;
const compressBtn = document.getElementById("compressBtn") as HTMLButtonElement;
const progressBar = document.getElementById(
"progressBar"
) as HTMLProgressElement;
const resultArea = document.getElementById("resultArea") as HTMLDivElement;
convertBtn.addEventListener("click", convertPdf);
compressBtn.addEventListener("click", compressPdf);
async function convertPdf() {
const file = fileInput.files?.[0];
if (!file) {
alert("Please select a file first");
return;
}
try {
resultArea.innerHTML = "Converting file...";
progressBar.value = 0;
progressBar.style.display = "block";
const result = await scanproApi.convertFile(file, "docx", {
onProgress: (progress) => {
progressBar.value = progress;
},
});
progressBar.style.display = "none";
resultArea.innerHTML = `
<div class="success-message">
<h3>File Converted Successfully!</h3>
<p>From: ${result.inputFormat} to: ${result.outputFormat}</p>
<a href="${result.fileUrl}" class="download-btn" download>Download Converted File</a>
</div>
`;
} catch (error) {
progressBar.style.display = "none";
resultArea.innerHTML = `
<div class="error-message">
<h3>Conversion Failed</h3>
<p>${error instanceof Error ? error.message : "Unknown error"}</p>
</div>
`;
}
}
async function compressPdf() {
const file = fileInput.files?.[0];
if (!file) {
alert("Please select a file first");
return;
}
try {
resultArea.innerHTML = "Compressing file...";
progressBar.value = 0;
progressBar.style.display = "block";
const result = await scanproApi.compressPdf(file, {
quality: "medium",
onProgress: (progress) => {
progressBar.value = progress;
},
});
progressBar.style.display = "none";
const reductionPercent =
(1 - result.compressedSize / result.originalSize) * 100;
resultArea.innerHTML = `
<div class="success-message">
<h3>File Compressed Successfully!</h3>
<p>Original size: ${formatFileSize(result.originalSize)}</p>
<p>Compressed size: ${formatFileSize(result.compressedSize)}</p>
<p>Reduction: ${reductionPercent.toFixed(2)}%</p>
<a href="${
result.fileUrl
}" class="download-btn" download>Download Compressed File</a>
</div>
`;
} catch (error) {
progressBar.style.display = "none";
resultArea.innerHTML = `
<div class="error-message">
<h3>Compression Failed</h3>
<p>${error instanceof Error ? error.message : "Unknown error"}</p>
</div>
`;
}
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
Conclusion
This guide covers all the operations available in the ScanPro API client. Use these examples as a starting point for integrating ScanPro's powerful document processing capabilities into your Next.js application.
For more complex use cases or custom workflows, you can combine multiple operations to create advanced document processing pipelines. For example, you could convert a document, compress it, and then add a watermark, all through a seamless user experience with progress tracking.
Remember to handle errors appropriately and provide feedback to users during file uploads and processing.