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 Bundle Laravel Package

bytes/docraptor-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle and its dependency to composer.json:

    composer require bytes/docraptor-bundle bytes/docraptor "@dev"
    

    Run composer update.

  2. Register the Bundle Add the bundle to config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 2/3):

    Bytes\Bundle\DocraptorBundle\BytesDocraptorBundle::class => ['all' => true],
    
  3. Configuration Publish the default config:

    php bin/console config:dump-reference BytesDocraptorBundle
    

    Override in config/packages/bytes_docraptor.yaml:

    bytes_docraptor:
        api_key: '%env(DOCRAPTOR_API_KEY)%'
        timeout: 30
    
  4. First Use Case: PDF Generation Inject the client into a controller/service:

    use Bytes\DocraptorBundle\Client\DocraptorClientInterface;
    
    public function __construct(DocraptorClientInterface $docraptor) {
        $this->docraptor = $docraptor;
    }
    
    public function generatePdf() {
        $job = $this->docraptor->createJob(
            'https://example.com/invoice.pdf',
            'https://example.com/html-content'
        );
        return $job->getUrl();
    }
    

Implementation Patterns

Common Workflows

  1. Job Creation & Management

    • HTML-to-PDF: Use createJob() with HTML URL and target PDF URL.
    • Polling Status: Chain getJob() with getStatus() in a loop:
      $job = $this->docraptor->getJob($jobId);
      while ($job->getStatus() !== 'finished') {
          sleep(2);
          $job = $this->docraptor->getJob($jobId);
      }
      
  2. Dynamic Content

    • Generate HTML dynamically (e.g., via Twig) and pass its URL to Docraptor:
      $htmlUrl = $this->generateTwigHtml($data);
      $job = $this->docraptor->createJob($pdfUrl, $htmlUrl);
      
  3. Error Handling

    • Wrap API calls in try-catch:
      try {
          $job = $this->docraptor->createJob($pdfUrl, $htmlUrl);
      } catch (\Bytes\DocraptorBundle\Exception\DocraptorException $e) {
          $this->handleDocraptorError($e);
      }
      
  4. Configuration Overrides

    • Use environment variables or parameter bags for API keys/endpoints:
      # config/packages/bytes_docraptor.yaml
      bytes_docraptor:
          api_key: '%env(resolve:DOCRAPTOR_API_KEY)%'
          endpoint: 'https://api.docraptor.eu/v1'
      
  5. Event-Driven Workflows

    • Listen for job completion via webhooks (Docraptor feature) and trigger Laravel events:
      // In a service
      event(new JobCompleted($job));
      

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Risk: Hardcoding API keys in config. Always use .env or parameter bags.
    • Fix: Validate DOCRAPTOR_API_KEY in config/packages/bytes_docraptor.yaml:
      bytes_docraptor:
          api_key: '%env(DOCRAPTOR_API_KEY)%'
      
      Add to .env.example:
      DOCRAPTOR_API_KEY=your_key_here
      
  2. Rate Limiting

    • Docraptor enforces rate limits (~100 requests/minute for free tier).
    • Solution: Implement exponential backoff in retries:
      $attempts = 0;
      $maxAttempts = 3;
      while ($attempts < $maxAttempts) {
          try {
              $job = $this->docraptor->createJob($pdfUrl, $htmlUrl);
              break;
          } catch (\Bytes\DocraptorBundle\Exception\RateLimitException $e) {
              $attempts++;
              sleep(2 ** $attempts);
          }
      }
      
  3. HTML URL Validity

    • Docraptor requires publicly accessible HTML URLs. Self-signed certs or local dev URLs (e.g., http://localhost) may fail.
    • Workaround: Use a tunneling service (e.g., ngrok) for local testing.
  4. Bundle Maturity

    • Warning: The bundle has low stars/maturity. Test thoroughly in staging.
    • Mitigation: Fork the repo and extend the DocraptorClientInterface for custom needs.
  5. Debugging API Calls

    • Enable debug mode in bytes_docraptor.yaml:
      bytes_docraptor:
          debug: true
      
    • Check logs for raw API responses in var/log/dev.log.

Tips

  1. Caching Job Results

    • Cache PDF URLs or job statuses to avoid redundant API calls:
      $pdfUrl = Cache::remember("docraptor_job_{$jobId}", 3600, function () use ($jobId) {
          return $this->docraptor->getJob($jobId)->getUrl();
      });
      
  2. Queue Delayed Jobs

    • Offload PDF generation to Laravel queues:
      Dispatch(new GeneratePdfJob($data))->delay(now()->addMinutes(5));
      
  3. Custom Headers

    • Extend the client to add headers (e.g., for authentication):
      $client = $this->docraptor->getClient();
      $client->setDefaultOption('headers', [
          'X-Custom-Header' => 'value',
      ]);
      
  4. Testing

    • Mock the DocraptorClientInterface in PHPUnit:
      $mock = $this->createMock(DocraptorClientInterface::class);
      $mock->method('createJob')->willReturn(new Job(['url' => 'test.pdf']));
      $this->app->instance(DocraptorClientInterface::class, $mock);
      
  5. Webhook Integration

    • Validate webhook signatures (Docraptor sends X-Signature header):
      $signature = $_SERVER['HTTP_X_SIGNATURE'];
      $isValid = hash_equals($signature, hash_hmac('sha256', $payload, $apiKey));
      
  6. Fallback for Offline

    • Implement a fallback (e.g., local PDF generation) if Docraptor is unreachable:
      try {
          $job = $this->docraptor->createJob($pdfUrl, $htmlUrl);
      } catch (\Exception $e) {
          $pdf = $this->generateLocalPdf($htmlContent);
          return $pdf->saveAs($pdfUrl);
      }
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle