New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

@caqil/scanpro-api-client

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

@caqil/scanpro-api-client

A TypeScript client for interacting with ScanPro's document processing APIs

latest
Source
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

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:

// Option 1: Using the provided client
import { ScanProApiClient } from "@/api/scanpro-client";

// Create an instance with default base URL (current site)
const scanproApi = new ScanProApiClient();

// Or with a specific base URL
const scanproApi = new ScanProApiClient("https://scanpro.cc");

// Option 2: Using the default exported instance
import scanproApi from "@/api/scanpro-client";

Authentication

The ScanPro API supports API key authentication for programmatic access.

// Set an API key
scanproApi.setApiKey("sk_your_api_key_here");

// Remove an API key
scanproApi.clearApiKey();

File Conversion

Convert files between various formats.

Basic Conversion

// Example: Convert a PDF to DOCX
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

// Convert PDF to DOCX with OCR and progress tracking
const result = await scanproApi.convertFile(file, "docx", {
  ocr: true, // Enable OCR for text extraction
  quality: 90, // Quality setting (0-100)
  password: "secret", // Password for protected PDFs
  onProgress: (progress) => {
    // Track upload progress
    console.log(`Upload progress: ${progress}%`);
    // Update UI with 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", // 'low', 'medium', or 'high'
  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", // 'low', 'medium', or 'high'
  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.

// Get files from a file input
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
const files = Array.from(fileInput.files || []);

if (files.length >= 2) {
  try {
    // Merge PDFs in their current order
    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

// Merge PDFs with a custom order (file indices)
const result = await scanproApi.mergePdfs(files, {
  order: [2, 0, 1], // Third file first, then first file, then second file
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  },
});

PDF Splitting

Split a PDF document into multiple files.

Basic Splitting by Page Ranges

// Split PDF by specific page ranges
const result = await scanproApi.splitPdf(pdfFile, {
  splitMethod: "range", // 'range', 'extract', or 'every'
  pageRanges: "1-3, 5, 7-9", // Page ranges to extract
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  },
});

console.log(`Created ${result.splitParts?.length} PDF parts`);
// Access individual parts
result.splitParts?.forEach((part, index) => {
  console.log(`Part ${index + 1}: Pages ${part.pages.join(", ")}`);
  console.log(`Download URL: ${part.fileUrl}`);
});

Extract Each Page as Separate PDF

// Extract each page as a separate PDF
const result = await scanproApi.splitPdf(pdfFile, {
  splitMethod: "extract",
});

Split Every N Pages

// Split every 2 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...");

  // Poll for status
  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 {
      // Still processing, check again in 2 seconds
      setTimeout(checkStatus, 2000);
    }
  };

  checkStatus();
}

PDF Page Rotation

Rotate pages in a PDF document.

// Rotate specific pages
const rotations = [
  { pageNumber: 1, angle: 90 }, // First page: 90 degrees clockwise
  { pageNumber: 2, angle: 180 }, // Second page: 180 degrees (upside down)
  { pageNumber: 3, angle: 270 }, // Third page: 270 degrees clockwise (90 CCW)
];

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

// Add a text watermark
const result = await scanproApi.watermarkPdf(pdfFile, {
  watermarkType: "text",
  text: "CONFIDENTIAL",
  textColor: "#FF0000", // Red color
  fontSize: 48,
  fontFamily: "Arial",
  opacity: 30, // 30% opacity
  rotation: 45, // 45-degree angle
  position: "center", // or 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'tile'
  pages: "all", // 'all', 'even', 'odd', or 'custom'
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  },
});

console.log(`Added watermark to ${result.pagesWatermarked} pages`);
console.log(`Download URL: ${result.fileUrl}`);

Image Watermark

// Add an image watermark
const imageFile = imageInput.files?.[0];

if (pdfFile && imageFile) {
  const result = await scanproApi.watermarkPdf(pdfFile, {
    watermarkType: "image",
    watermarkImage: imageFile,
    scale: 50, // 50% of original size
    opacity: 30, // 30% opacity
    rotation: 0, // No rotation
    position: "bottom-right", // Position at bottom-right
    pages: "custom", // Use custom page selection
    customPages: "1-5, 10", // Pages 1-5 and page 10
    onProgress: (progress) => {
      console.log(`Upload progress: ${progress}%`);
    },
  });
}

Custom Position Watermark

// Add a watermark with custom position
const result = await scanproApi.watermarkPdf(pdfFile, {
  watermarkType: "text",
  text: "DRAFT",
  position: "custom",
  customX: 25, // 25% from the left
  customY: 75, // 75% from the top
  // Other options...
});

PDF Protection & Security

Protect PDFs with passwords or unlock protected PDFs.

Check if a PDF is Password Protected

// Check if a PDF is password protected
const checkResult = await scanproApi.checkPdfProtection(pdfFile);

if (checkResult.isPasswordProtected) {
  console.log("This PDF is password protected");
  // Prompt for password
} else {
  console.log("This PDF is not password protected");
}

Protect a PDF with Password

// Add password protection to a PDF
const result = await scanproApi.protectPdf(pdfFile, "your_password", {
  permission: "restricted", // 'all' or 'restricted'
  allowPrinting: true,
  allowCopying: false,
  allowEditing: false,
  protectionLevel: "256", // Encryption level
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  },
});

console.log(`PDF protected successfully`);
console.log(`Download URL: ${result.fileUrl}`);

Unlock a Protected PDF

// Unlock a password-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.

// Repair a corrupted PDF
const result = await scanproApi.repairPdf(pdfFile, {
  repairMode: "standard", // 'standard', 'advanced', or 'optimization'
  password: "pdf_password", // If the PDF is password-protected
  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.

// Add page numbers to a PDF
const result = await scanproApi.addPageNumbers(pdfFile, {
  format: "numeric", // 'numeric', 'roman', or 'alphabetic'
  position: "bottom-center", // Position on the page
  fontFamily: "Arial",
  fontSize: 12,
  color: "#000000", // Black
  startNumber: 1, // Start numbering from 1
  prefix: "Page ", // Text before number
  suffix: "", // Text after number
  marginX: 40, // Horizontal margin
  marginY: 30, // Vertical margin
  selectedPages: "1-5", // Only number pages 1-5
  skipFirstPage: true, // Skip the first page
  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.

// Get PDF information
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

// Process a PDF for editing (converts to images)
const result = await scanproApi.processPdfForEditing(pdfFile, {
  onProgress: (progress) => {
    console.log(`Upload progress: ${progress}%`);
  },
});

console.log(`Processed ${result.pageCount} pages for editing`);

// Store the session ID and page information for later use
const sessionId = result.sessionId;
const pages = result.pages;

// Pages contain URLs to images that can be edited in the UI
pages.forEach((page, index) => {
  console.log(`Page ${index + 1} image: ${page.imageUrl}`);
  console.log(`Dimensions: ${page.width} x ${page.height}`);
});

Save Edited PDF

// Save edits made to PDF pages
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.

// Process a PDF for signing
const processResult = await scanproApi.processPdfForEditing(pdfFile);

// Create signature elements
const signatureElements = [
  {
    id: "1",
    type: "signature",
    position: { x: 100, y: 500 },
    size: { width: 200, height: 50 },
    data: "data:image/png;base64,...", // Signature image data
    rotation: 0,
    scale: 1,
    page: 0, // First page (0-based index)
  },
  {
    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: "", // Will be filled with current date
    rotation: 0,
    scale: 1,
    page: 0,
    fontSize: 12,
    fontFamily: "Arial",
    color: "#000000",
  },
];

// Sign the PDF
const signResult = await scanproApi.signPdf(
  pdfFile,
  signatureElements,
  processResult.pages,
  {
    performOcr: true, // Make the PDF searchable
    ocrLanguage: "eng", // OCR language
    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

// Start a chat session with a PDF
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}`);

// Store the session ID for future messages
const sessionId = chatResult.sessionId;

Send Messages and Get Responses

// Send a message to the AI
const messageResult = await scanproApi.sendChatMessage(
  sessionId,
  "What is the main topic of this document?"
);

console.log(`AI: ${messageResult.message}`);

// Send another message
const followUpResult = await scanproApi.sendChatMessage(
  sessionId,
  "Can you summarize the key points?"
);

console.log(`AI: ${followUpResult.message}`);

Get Chat History

// Get the full 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

// Delete the chat session when done
await scanproApi.deleteChatSession(sessionId);
console.log("Chat session deleted");

Managing API Keys

Generate, list, and revoke API keys for programmatic access.

Generate API Key

// Generate a new API key
const keyResult = await scanproApi.generateApiKey(
  "Development API Key",
  ["convert", "compress", "merge", "split"] // Specific permissions
);

console.log(`API Key created: ${keyResult.key.name}`);
console.log(`Key value: ${keyResult.key.key}`); // Store this securely
console.log(`Permissions: ${keyResult.key.permissions.join(", ")}`);

List API Keys

// List all 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}`); // Masked for security
  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

// Revoke an 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);

    // Show error to user
    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";

// Create an instance
const scanproApi = new ScanProApiClient();

// DOM elements
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;

// Set up event listeners
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";

    // Show result and download link
    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";

    // Calculate size reduction percentage
    const reductionPercent =
      (1 - result.compressedSize / result.originalSize) * 100;

    // Show result and download link
    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>
    `;
  }
}

// Utility function for formatting file size
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.

Keywords

scanpro

FAQs

Package last updated on 19 Apr 2025

Related posts