PHP code example of codewithathis / paperless-ngx

1. Go to this page and download the library: Download codewithathis/paperless-ngx library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codewithathis / paperless-ngx example snippets


'auth' => [
    'token' => env('PAPERLESS_TOKEN', null),
    'username' => env('PAPERLESS_USERNAME', null),
    'password' => env('PAPERLESS_PASSWORD', null),
    'method' => env('PAPERLESS_AUTH_METHOD', 'auto'),
],

'upload' => [
    'max_file_size' => env('PAPERLESS_MAX_FILE_SIZE', 50 * 1024 * 1024),
    'allowed_mime_types' => [
        'application/pdf',
        'image/jpeg',
        'image/png',
        'image/tiff',
        // ... more types
    ],
    'auto_ocr' => env('PAPERLESS_AUTO_OCR', true),
    'auto_tag' => env('PAPERLESS_AUTO_TAG', false),
],

use Codewithathis\PaperlessNgx\PaperlessService;

class DocumentController extends Controller
{
    public function __construct(private PaperlessService $paperlessService)
    {
    }

    public function index()
    {
        $documents = $this->paperlessService->getDocuments();
        return response()->json($documents);
    }
}

use Codewithathis\PaperlessNgx\Facades\Paperless;

// Test connection
$isConnected = Paperless::testConnection();

// Get documents
$documents = Paperless::getDocuments(['title__icontains' => 'invoice']);

// Upload document
$documentId = Paperless::uploadDocument($file, [
    'title' => 'Invoice #123',
    'correspondent' => 1,
    'tags' => [1, 2, 3],
]);

// Set token
$paperlessService->setToken('your_api_token');

// Or in constructor
$paperlessService = new PaperlessService(
    'http://your-paperless-instance.com',
    'your_api_token'
);

// Set credentials
$paperlessService->setBasicAuth('username', 'password');

// Or in constructor
$paperlessService = new PaperlessService(
    'http://your-paperless-instance.com',
    null,
    'username',
    'password'
);

use Illuminate\Http\UploadedFile;

$file = $request->file('document');
$metadata = [
    'title' => 'Invoice #123',
    'correspondent' => 1,
    'document_type' => 2,
    'tags' => [1, 2, 3],
    'storage_path' => 1,
    'archive_serial_number' => 1001,
];

$documentId = $paperlessService->uploadDocument($file, $metadata);

$filters = [
    'title__icontains' => 'invoice',
    'correspondent__id' => 1,
    'tags__id__in' => [1, 2, 3],
    'created__gte' => '2024-01-01',
    'created__lte' => '2024-12-31',
];

$documents = $paperlessService->getDocuments($filters, 1, 25);

$data = [
    'title' => 'Updated Invoice Title',
    'correspondent' => 2,
    'tags' => [1, 4, 5],
];

$document = $paperlessService->updateDocument(123, $data);

// Download processed version
$content = $paperlessService->downloadDocument(123);

// Download original version
$originalContent = $paperlessService->downloadDocument(123, true);

$deleted = $paperlessService->deleteDocument(123);

// Search in database only
$results = $paperlessService->searchDocuments('invoice', true);

// Search in full content
$results = $paperlessService->searchDocuments('invoice', false);

$suggestions = $paperlessService->getSearchAutocomplete('inv', 10);

$documentIds = [1, 2, 3, 4, 5];
$editData = [
    'correspondent' => 1,
    'tags' => [1, 2],
    'document_type' => 2,
];

$result = $paperlessService->bulkEditDocuments($documentIds, $editData);

$documentIds = [1, 2, 3, 4, 5];
$downloadInfo = $paperlessService->bulkDownloadDocuments($documentIds);

// Get all tags
$tags = $paperlessService->getTags();

// Create tag
$tag = $paperlessService->createTag([
    'name' => 'Important',
    'color' => '#ff0000',
]);

// Update tag
$updatedTag = $paperlessService->updateTag(1, [
    'name' => 'Very Important',
    'color' => '#00ff00',
]);

// Delete tag
$deleted = $paperlessService->deleteTag(1);

// Get correspondents
$correspondents = $paperlessService->getCorrespondents();

// Create correspondent
$correspondent = $paperlessService->createCorrespondent([
    'name' => 'ABC Company',
    'matching_algorithm' => 1,
    'match' => 'ABC',
]);

// Update correspondent
$updatedCorrespondent = $paperlessService->updateCorrespondent(1, [
    'name' => 'ABC Corporation',
]);

// Delete correspondent
$deleted = $paperlessService->deleteCorrespondent(1);

// Get document types
$documentTypes = $paperlessService->getDocumentTypes();

// Create document type
$documentType = $paperlessService->createDocumentType([
    'name' => 'Invoice',
    'matching_algorithm' => 1,
    'match' => 'invoice',
]);

// Update document type
$updatedDocumentType = $paperlessService->updateDocumentType(1, [
    'name' => 'Invoice Document',
]);

// Delete document type
$deleted = $paperlessService->deleteDocumentType(1);

// Get document notes
$notes = $paperlessService->getDocumentNotes(123);

// Add note
$note = $paperlessService->addDocumentNote(123, 'This is an important document');

// Delete note
$deleted = $paperlessService->deleteDocumentNote(123, 1);

// Get document history
$history = $paperlessService->getDocumentHistory(123);

// Get document share links
$shareLinks = $paperlessService->getDocumentShareLinks(123);

// Create share link
$shareLink = $paperlessService->createShareLink([
    'document' => 123,
    'expiration' => '2024-12-31',
]);

// Update share link
$updatedShareLink = $paperlessService->updateShareLink(1, [
    'expiration' => '2024-06-30',
]);

// Delete share link
$deleted = $paperlessService->deleteShareLink(1);

// Get system statistics
$statistics = $paperlessService->getStatistics();

// Get system status
$status = $paperlessService->getStatus();

// Get remote version
$version = $paperlessService->getRemoteVersion();

// Get user profile
$profile = $paperlessService->getProfile();

// Generate auth token
$token = $paperlessService->generateAuthToken();

use Codewithathis\PaperlessNgx\Exceptions\PaperlessApiException;
use Codewithathis\PaperlessNgx\Exceptions\PaperlessConnectionException;

try {
    $documents = $paperlessService->getDocuments();
} catch (PaperlessApiException $e) {
    // Handle API errors (4xx, 5xx status codes)
    $statusCode = $e->getStatusCode();
    $responseData = $e->getResponseData();
    
    if ($e->isAuthenticationError()) {
        return response()->json(['error' => 'Authentication failed'], 401);
    }
    
    return response()->json(['error' => $e->getMessage()], $statusCode);
} catch (PaperlessConnectionException $e) {
    // Handle connection issues
    return response()->json(['error' => 'Service unavailable'], 503);
}

use Codewithathis\PaperlessNgx\Exceptions\PaperlessExceptionHandler;

try {
    $result = $paperlessService->uploadDocument($file, $metadata);
} catch (PaperlessException $e) {
    $errorResponse = PaperlessExceptionHandler::handle($e);
    $httpStatusCode = PaperlessExceptionHandler::getHttpStatusCode($e);
    
    return response()->json($errorResponse, $httpStatusCode);
}

'logging' => [
    'enabled' => env('PAPERLESS_LOGGING_ENABLED', true),
    'level' => env('PAPERLESS_LOG_LEVEL', 'error'),
    'channel' => env('PAPERLESS_LOG_CHANNEL', 'paperless'),
],

'cache' => [
    'enabled' => env('PAPERLESS_CACHE_ENABLED', true),
    'ttl' => env('PAPERLESS_CACHE_TTL', 3600),
    'prefix' => env('PAPERLESS_CACHE_PREFIX', 'paperless'),
],

'security' => [
    'verify_ssl' => env('PAPERLESS_VERIFY_SSL', true),
    'allow_self_signed' => env('PAPERLESS_ALLOW_SELF_SIGNED', false),
    'timeout' => env('PAPERLESS_REQUEST_TIMEOUT', 30),
],

// Test connection
$isConnected = $paperlessService->testConnection();

if ($isConnected) {
    echo "Successfully connected to Paperless-ngx";
} else {
    echo "Failed to connect to Paperless-ngx";
}

use Codewithathis\PaperlessNgx\PaperlessService;
use Illuminate\Http\UploadedFile;

class DocumentService
{
    public function __construct(private PaperlessService $paperlessService)
    {
    }

    public function processInvoice(UploadedFile $file, array $data)
    {
        try {
            // 1. Upload document
            $documentId = $this->paperlessService->uploadDocument($file, [
                'title' => $data['title'],
                'correspondent' => $data['correspondent_id'],
                'document_type' => $data['document_type_id'],
                'tags' => $data['tag_ids'],
            ]);

            // 2. Add note
            $this->paperlessService->addDocumentNote($documentId, 'Processed automatically');

            // 3. Get document details
            $document = $this->paperlessService->getDocument($documentId);

            return [
                'success' => true,
                'document_id' => $documentId,
                'document' => $document,
            ];
        } catch (Exception $e) {
            Log::error('Failed to process invoice', [
                'error' => $e->getMessage(),
                'file' => $file->getClientOriginalName(),
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage(),
            ];
        }
    }

    public function searchInvoices(string $query)
    {
        $filters = [
            'title__icontains' => $query,
            'document_type__name__icontains' => 'invoice',
        ];

        return $this->paperlessService->getDocuments($filters);
    }

    public function bulkTagDocuments(array $documentIds, array $tagIds)
    {
        return $this->paperlessService->bulkEditDocuments($documentIds, [
            'tags' => $tagIds,
        ]);
    }
}

use Codewithathis\PaperlessNgx\PaperlessService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessDocumentJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        private string $filePath,
        private array $metadata
    ) {
    }

    public function handle(PaperlessService $paperlessService)
    {
        $file = new UploadedFile($this->filePath, basename($this->filePath));
        
        $documentId = $paperlessService->uploadDocument($file, $this->metadata);
        
        // Process the uploaded document
        Log::info('Document uploaded successfully', ['document_id' => $documentId]);
    }
}
bash
php artisan vendor:publish --provider="Codewithathis\PaperlessNgx\PaperlessServiceProvider" --tag="paperless-config"
bash
php artisan paperless:test
bash
php artisan paperless:test --search="invoice"

codewithathis/paperless-ngx/
├── src/
│   ├── PaperlessService.php
│   ├── PaperlessServiceProvider.php
│   ├── Facades/
│   │   └── Paperless.php
│   ├── Http/
│   │   └── Controllers/
│   │       └── PaperlessController.php
│   └── Commands/
│       └── TestPaperlessConnection.php
├── config/
│   └── paperless.php
├── routes/
│   └── api.php
├── composer.json
└── README.md
bash
# Run the test command
php artisan paperless:test

# Test with file upload
php artisan paperless:test --upload=/path/to/test.pdf

# Test search functionality
php artisan paperless:test --search="invoice"