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

Pdf Bundle Laravel Package

bushidoio/pdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bushidoio/pdf-bundle:dev-master
    

    Enable the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3-):

    BushidoIO\PDFBundle\BushidoIOPDFBundle::class => ['all' => true],
    
  2. First Use Case: Generate a PDF from an HTML string in a controller:

    use BushidoIO\PDFBundle\Service\PDFService;
    
    public function generatePdf(PDFService $pdfService)
    {
        $html = '<h1>Hello, PDF!</h1><p>This is generated from HTML.</p>';
        $pdf = $pdfService->htmlToPdf($html);
        return new Response($pdf, 200, ['Content-Type' => 'application/pdf']);
    }
    
  3. Key Files:

    • config/packages/bushidoio_pdf.yaml (Symfony 4+)
    • app/config/config.yml (Symfony 3-)
    • Service: bushidoio_pdf (autowired or fetched via get()).

Implementation Patterns

Core Workflow

  1. HTML-to-PDF Conversion: Inject PDFService into controllers/services and use:

    $pdfContent = $pdfService->htmlToPdf($htmlString, [
        'format' => 'A4', // Optional: 'A3', 'A5', etc.
        'orientation' => 'portrait', // 'landscape'
        'margin_top' => 10, // in mm
        'margin_bottom' => 10,
        'margin_left' => 10,
        'margin_right' => 10,
    ]);
    
  2. Response Handling: Return a Response with PDF content:

    return new Response(
        $pdfContent,
        200,
        ['Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="document.pdf"']
    );
    
  3. Dynamic HTML Generation: Combine with Twig to render templates before conversion:

    $html = $this->renderView('path/to/template.html.twig', ['data' => $data]);
    $pdf = $pdfService->htmlToPdf($html);
    

Integration Tips

  • Font Management: Place custom TTF fonts in ttffontdatapath (configured in config.yml) and reference them in HTML:

    <style>@font-face { font-family: 'CustomFont'; src: url('/fonts/CustomFont.ttf'); }</style>
    

    Ensure the path is accessible from the HTML context.

  • Caching: Use the tmp directory (default: app/cache/bushidoio_pdf/tmp) for temporary files. Clear it manually if needed:

    rm -rf var/cache/bushidoio_pdf/tmp/*
    
  • Batch Processing: For multiple PDFs, reuse the PDFService instance (it’s a singleton) and loop through HTML strings:

    foreach ($htmlStrings as $html) {
        $pdfs[] = $pdfService->htmlToPdf($html);
    }
    
  • Symfony Forms: Generate PDFs from form submissions:

    public function submitFormAction(Request $request, PDFService $pdfService)
    {
        $form = $this->createForm(...);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $html = $this->renderView('form/pdf_template.html.twig', ['form' => $form->createView()]);
            return new Response($pdfService->htmlToPdf($html), 200, ['Content-Type' => 'application/pdf']);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Font Paths:

    • If fonts fail to load, verify:
      • The ttffontdatapath in config.yml is correct and writable.
      • Font files are accessible via the URL in HTML (e.g., /fonts/CustomFont.ttf must resolve to the actual file).
    • Fix: Use absolute paths in HTML or ensure the web server serves the font directory.
  2. Permissions:

    • The tmp and ttffontdatapath directories must be writable by the web server user.
    • Fix: Run chmod -R 775 var/cache/bushidoio_pdf (adjust paths as needed).
  3. HTML/CSS Limitations:

    • Complex CSS (e.g., position: absolute, float) may render unpredictably in PDFs.
    • Tip: Test PDF output early and simplify CSS if needed.
  4. Memory Issues:

    • Generating large PDFs may exhaust memory.
    • Tip: Use ini_set('memory_limit', '512M') in a controller or service constructor if needed.
  5. Dev-Master Dependency:

    • The package is in dev-master state, which may introduce breaking changes.
    • Tip: Monitor the repository for updates or fork it for stability.

Debugging

  1. Check Temporary Files: Inspect var/cache/bushidoio_pdf/tmp/ for generated files (e.g., .html or .pdf intermediates).

  2. Log Errors: Enable Symfony’s monolog to catch exceptions:

    # config/packages/monolog.yaml
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
    
  3. Validate HTML: Use browser dev tools to ensure HTML renders correctly before PDF conversion.

Extension Points

  1. Customize PDF Options: Extend the service by overriding the default configuration:

    # config/packages/bushidoio_pdf.yaml
    bushidoio_pdf:
        tmp: "%kernel.project_dir%/var/cache/bushidoio_pdf/tmp"
        ttffontdatapath: "%kernel.project_dir%/public/fonts"
        default_options:
            format: 'Letter'
            orientation: 'landscape'
    
  2. Add Headers/Footers: Inject custom HTML via the options array:

    $pdfService->htmlToPdf($html, [
        'header_html' => '<div style="text-align: center;">Header Content</div>',
        'footer_html' => '<div style="text-align: center;">Footer Content</div>',
    ]);
    
  3. Event Listeners: Hook into PDF generation by creating a custom event subscriber (if the bundle supports events; check the source for Events class).

  4. Alternative Renderers: If the underlying library (e.g., Dompdf or wkhtmltopdf) is configurable, extend the bundle’s service to pass additional options:

    // Override the service in config/services.yaml
    services:
        BushidoIO\PDFBundle\Service\PDFService:
            arguments:
                $options: ['custom_option' => 'value']
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui