Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Docraptor Laravel Package

bytes/docraptor

Lightweight PHP 5 DocRaptor API client to convert HTML into PDF or Excel. Create a document, set HTML content, and send it via cURL with your DocRaptor API key. Supports test mode and exception handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require bytes/docraptor:dev-master
    

    Ensure your PHP environment meets the requirements (PHP >= 5.3.2 with cURL).

  2. First Use Case: Convert HTML to PDF

    use Bytes\Docraptor\Document\PdfDocument;
    use Bytes\Docraptor\Http\Client as HttpClient;
    use Bytes\Docraptor\Client;
    
    $document = new PdfDocument('invoice');
    $document->setContent('<h1>Hello, DocRaptor!</h1><p>This is a test.</p>');
    
    $httpClient = new HttpClient();
    $client = new Client($httpClient, env('DOCRAPTOR_API_KEY'));
    
    $pdf = $client->setTestMode(true)->convert($document);
    file_put_contents('output.pdf', $pdf->getContent());
    
  3. Where to Look First

    • Document Classes: Explore PdfDocument and ExcelDocument in src/Document/ for supported formats.
    • Client Configuration: Review Client class in src/Client.php for API key, test mode, and timeout settings.
    • HTTP Client: Customize HttpClient in src/Http/ for proxy or authentication needs.

Implementation Patterns

Core Workflows

  1. Document Conversion

    • PDF/Excel Generation:
      $document = new PdfDocument('report');
      $document->setContent($htmlContent);
      $client->convert($document); // Returns a `Document` object with binary content.
      
    • Streaming to User:
      return response($pdf->getContent(), 200, [
          'Content-Type' => 'application/pdf',
          'Content-Disposition' => 'attachment; filename="report.pdf"',
      ]);
      
  2. Configuration Management

    • Test Mode: Enable for debugging (avoids charges):
      $client->setTestMode(true);
      
    • Timeouts: Override HTTP client defaults:
      $httpClient = new HttpClient(['timeout' => 30]);
      
  3. Integration with Laravel

    • Service Provider: Bind the client to the container:
      $this->app->singleton(Client::class, function ($app) {
          $httpClient = new HttpClient();
          return new Client($httpClient, config('services.docraptor.key'));
      });
      
    • Facade (Optional): Create a facade for cleaner syntax:
      // app/Facades/DocRaptor.php
      public static function convertPdf($html, $name) {
          return app(Client::class)->convert(new PdfDocument($name)->setContent($html));
      }
      
  4. Batch Processing

    • Queue conversions for async handling:
      Dispatch(new ConvertDocument($document, $userId))->onQueue('docraptor');
      

Gotchas and Tips

Pitfalls

  1. API Key Management

    • Hardcoded Keys: Avoid committing API keys to version control. Use Laravel’s .env:
      DOCRAPTOR_API_KEY=your_key_here
      
    • Key Rotation: Update the key in the client if compromised or revoked.
  2. Error Handling

    • Exception Types: Catch DocraptorException for API errors (e.g., invalid HTML, rate limits).
      try {
          $client->convert($document);
      } catch (DocraptorException $e) {
          Log::error('DocRaptor failed: ' . $e->getMessage());
          return back()->withError('Failed to generate document.');
      }
      
    • HTTP Client Errors: Wrap HttpClient calls to handle network issues:
      try {
          $response = $httpClient->post($url, $data);
      } catch (Exception $e) {
          // Retry logic or fallback
      }
      
  3. Content Validation

    • HTML Sanitization: DocRaptor may reject malformed HTML. Sanitize input:
      use Illuminate\Support\Str;
      $cleanHtml = Str::of($userInput)->markdown()->toHtml();
      $document->setContent($cleanHtml);
      
  4. Rate Limits

    • Test Mode: Always disable in production to avoid hitting API limits:
      // Production
      $client->setTestMode(false);
      

Tips

  1. Custom HTTP Client

    • Extend HttpClient to add headers or logging:
      class CustomHttpClient extends HttpClient {
          public function __construct() {
              parent::__construct(['headers' => ['X-Custom-Header' => 'value']]);
          }
      }
      
  2. Document Metadata

    • Set additional metadata (e.g., margins, page size) via setOptions():
      $document->setOptions([
          'margin_top' => '0.5in',
          'margin_bottom' => '0.5in',
      ]);
      
  3. Excel-Specific Features

    • Use ExcelDocument for spreadsheets:
      $excel = new ExcelDocument('spreadsheet');
      $excel->setContent('<table><tr><td>Data</td></tr></table>');
      $client->convert($excel);
      
  4. Debugging

    • Enable verbose logging in HttpClient:
      $httpClient = new HttpClient(['verbose' => true]);
      
    • Check DocRaptor’s API Status for outages.
  5. Performance

    • Caching: Cache converted documents if they’re static:
      $pdf = Cache::remember("doc_{$documentId}", 3600, function () use ($client, $document) {
          return $client->convert($document);
      });
      
  6. Extensions

    • Webhooks: Use DocRaptor’s webhooks for async notifications (requires server-side handling).
    • Storage: Integrate with Laravel’s filesystem:
      Storage::disk('s3')->put('documents/report.pdf', $pdf->getContent());
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity