Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › APITemplate.io

How to Convert an HTML Invoice to PDF with APITemplate.io in Laravel

By Freedom251 Team · · 7 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To convert an HTML invoice to PDF in Laravel, send the invoice markup to APITemplate.io’s POST /v2/create-pdf-from-html endpoint as JSON, authenticate with the X-API-KEY header, and read the returned download_url. If the same invoice layout is used repeatedly, a saved APITemplate.io template with invoice data sent as JSON can be easier to maintain.

Choose raw HTML or a reusable invoice template

Approach Best fit Where the layout lives Request input
Raw HTML: /v2/create-pdf-from-html Invoices assembled dynamically in Laravel or a one-off document Your Laravel application HTML body, optionally CSS, Jinja2 data and PDF settings
Reusable template: /v2/create-pdf A recurring invoice design APITemplate.io’s template editor Template ID and invoice fields as JSON

This guide uses raw HTML because it is the direct route from an HTML invoice to PDF. The template route is useful when you want to keep a repeated layout separate from the values for each invoice. The provider describes both workflows; available documentation does not establish that either is faster or cheaper. APITemplate.io generation documentation

As an Amazon Associate I earn from qualifying purchases.

Generate a PDF from HTML with Laravel’s HTTP client

The raw HTML endpoint is POST https://rest.apitemplate.io/v2/create-pdf-from-html. Send a JSON object containing body, the HTML string. The documented optional fields include css, data for Jinja2 placeholders and settings for page configuration. Authenticate with the X-API-KEY header. A successful response includes download_url, transaction_ref and status. Check the current endpoint documentation for accepted setting names and values before relying on them, as API details can change. Raw HTML endpoint reference

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure the API key

Keep the key on the server, not in browser JavaScript or invoice HTML. For example, set an environment variable:

#1 Best Overall
Brother DCP-L2640DW Wireless Compact Monochrome Multi-Function Printer, Copy, Scan, Duplex, Mobile Printing
  • BEST FOR SMALL BUSINESSES – Engineered for extraordinary productivity, the Brother DCP-L2640DW Monochrome (Black & White) 3-in-1 combines laser printer, scanner, copier in one compact footprint and delivers high-quality black & white prints
  • FAST PRINTER WITH EFFICIENT SCANNING – Produces documents quickly with print speeds up to 36 ppm(2) and scan speeds up to 23.6/7.9 ipm(3) (black/color). A 50-page auto document feeder(4) allows for convenient, time saving multi-page scanning and copying
  • FLEXIBLE CONNECTION OPTIONS – Easily navigate the changing demands of your business with secure multi-device connectivity via built-in dual-band wireless (2.4GHz / 5GHz) and Ethernet. Or connect locally to a single computer via USB interface
  • BROTHER MOBILE CONNECT APP – Print, scan, and manage your wireless printer anytime, from almost anywhere from your mobile device. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(5)
  • CHOOSE BROTHER GENUINE TONER – When it’s time to replace your toner, be sure to choose Brother Genuine TN830 or TN830XL replacement toner. And with Refresh EZ Print Subscription Service, you’ll never worry about running out of toner again and you’ll enjoy savings of up to 50%(6) on Brother Genuine Toner. Get started with Refresh today with a Free Trial(1)
APITEMPLATE_API_KEY=your_api_key

Expose it through Laravel configuration, such as config/services.php:

'apitemplate' => [
    'key' => env('APITEMPLATE_API_KEY'),
],

Then access it in application code with config('services.apitemplate.key'). Avoid logging the key or sensitive invoice data.

Send the invoice and inspect the response

This example assumes $invoiceHtml and $invoiceCss have already been generated by your application. It uses Laravel’s HTTP client to send JSON, applies a 100-second timeout, throws for HTTP error responses, and checks for a usable URL before returning it:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Brother HL-L2405W Wireless Compact Monochrome Laser Printer with Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • BEST FOR HOMES & HOME OFFICES – Engineered for consistent, premium print quality, the Brother HL-L2405W Monochrome (Black & White) Laser Printer delivers sharp, crisp prints at an affordable price. Prints one-sided documents at speeds up to 30ppm(2)
  • COMPACT, CONNECTED PRINTER – Flexible connection options make this an ideal printer for home use and at-home offices. Securely connect to multiple devices with built-in dual-band wireless (2.4GHz/5GHz) or locally to a single computer via USB interface
  • BROTHER MOBILE CONNECT APP – Manage your printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
  • VERSATILE PAPER HANDLING – Enjoy seamless, reliable everyday printing with the 250-sheet paper tray(4) and a manual feed slot that enables printing on envelopes and specialty pape
  • BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer
use IlluminateSupportFacadesHttp;
use RuntimeException;

$response = Http::withHeaders([
    'X-API-KEY' => config('services.apitemplate.key'),
    'Accept' => 'application/json',
])->timeout(100)->post(
    'https://rest.apitemplate.io/v2/create-pdf-from-html',
    [
        'body' => $invoiceHtml,
        'css' => $invoiceCss,
        'settings' => [
            'paper_size' => 'A4',
            'orientation' => '1',
            'print_background' => '1',
        ],
    ]
)->throw();

$pdfUrl = $response->json('download_url');

if (! is_string($pdfUrl) || $pdfUrl === '') {
    throw new RuntimeException('APITemplate.io did not return a PDF download URL.');
}

The paper size, orientation and background keys above follow the provider’s documented example. Verify that the names and accepted values remain current for your account and endpoint. The sample timeout is illustrative: it follows a maximum shown in the provider’s PHP client repository, but your application’s HTTP, worker and user-response budgets may require a shorter limit. Laravel documents that timeouts raise connection exceptions; choose a value compatible with your deployment. Laravel 13.x HTTP client documentation · APITemplate.io PHP client repository

Return or retrieve the PDF

Once you have a non-empty download_url, your application can return it to the caller or retrieve the file server-side. Validate the response before using the URL; do not assume its lifetime, retention policy or access controls from the fact that it was returned. Those details are not established here, so check the provider’s current terms and documentation if your workflow depends on them.

Use a saved template for invoices with a repeating layout

  1. In the APITemplate.io console, create a PDF template using the HTML editor. The HTML editor provides control over HTML, CSS and JavaScript; the provider also describes a visual editor for simpler layouts where that level of control is not needed.
  2. Add Jinja2 placeholders for invoice values, such as {{invoice_number}}, and use loops for line items where appropriate. The editor supports variables, loops and conditionals.
  3. Use the template preview and sample JSON workflow to check how the supplied values render.
  4. From Laravel, send invoice fields as JSON to POST /v2/create-pdf?template_id=YOUR_TEMPLATE_ID, with the X-API-KEY header.
  5. Check the response for its PDF download_url before passing it to another part of your application.

With this arrangement, the layout stays in the template while each Laravel request supplies that invoice’s data. Consult the current API reference for the full request format and endpoint behavior. APITemplate.io documentation · Template PDF endpoint reference

Rank #3
Sale
Canon imageCLASS LBP6030w - Monochrome Single-Function Wireless Compact Wireless Laser Printer, 1 Year Limited Warranty, 19 PPM, White - Print Only
  • FAST PRINT SPEEDS: Print up to 19 pages per minute.
  • COMPACT DESIGN: Space-saving, compact design fits anywhere in your home, school or small office.
  • WIRELESS CONNECTIVITY: Print from almost anywhere in your workspace using your compatible mobile device.
  • PAPER CAPACITY: Up to 150 sheets.
  • SUSTAINABILITY: Uses less than 2 watts in Energy Saver mode.

Configure page appearance and dynamic content

CSS, backgrounds and page settings

For raw HTML generation, the request can include a separate css value and settings for output configuration. The provider’s example includes paper size, orientation, margins and printing the background. Its documentation describes Chromium-based CSS and JavaScript rendering and support for headers, footers, page numbers, paper size and margins. Confirm the exact setting names and allowed values in the live endpoint documentation before implementing page-specific behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Jinja2 data

The optional data field supplies values for Jinja2 placeholders in the HTML body. This lets you keep some markup as a template while still submitting it through the raw HTML endpoint. If the layout itself is a stable, recurring invoice, a saved template is another way to separate layout from invoice data.

Handle timeouts, failures and sensitive data

  • Set a deliberate timeout. Laravel’s timeout() limits how long the client waits; a timeout raises a connection exception. Match it to your application’s response budget, queue-worker limits and the provider region you use.
  • Handle non-success HTTP responses. Laravel’s HTTP client does not automatically throw for 4xx or 5xx responses. Use throw() when an unsuccessful status should interrupt the flow, or inspect the status and return a controlled application error.
  • Consider asynchronous work for longer tasks. APITemplate.io documents synchronous and asynchronous generation and webhook notifications in its methods overview. A Laravel queue can be an application-level way to keep slow or bulk generation out of a user-facing request, but confirm the current endpoint’s callback behavior before implementing a webhook flow. APITemplate.io methods documentation
  • Protect keys and invoice contents. Keep credentials and customer or payment details out of browser code and logs. For sensitive invoice data, consult the provider’s current privacy and retention terms; the endpoint details alone do not establish a complete data-handling policy.
  • Account for region-specific limits. The provider’s PHP client repository lists endpoint limits that vary by region and API mode. Check the current settings for your deployment rather than assuming one timeout or limit applies everywhere.

Troubleshoot common Laravel integration errors

Symptom Likely cause What to check
401 or another authentication error The API key is missing, invalid or not sent in the expected header. Confirm config('services.apitemplate.key') resolves on the running environment and that the request includes X-API-KEY.
4xx response The request body or settings may not match the endpoint’s current schema. Confirm the URL, JSON payload, required body field and current accepted names and values for settings in the endpoint reference.
Laravel continues after an HTTP error Laravel does not throw automatically for 4xx and 5xx status codes. Call throw() or handle $response->successful() and status codes explicitly.
Connection exception or timeout Rendering exceeded the configured wait, the network failed, or the timeout conflicts with the endpoint or deployment limits. Choose a timeout within your application and provider limits; for work that should not block a web request, consider a queued flow and confirm the provider’s asynchronous behavior.
No usable download_url The response may not be a successful generation result, or its shape may have changed. Inspect the status and response body safely, handle errors, and validate the URL before redirecting or fetching it.
Unexpected invoice appearance The HTML, CSS, Jinja2 data or page settings may not be rendering as expected. Check the rendered markup and supplied values, verify current setting names, and use the provider’s template preview workflow when using a saved template.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a web page rather than generate a formatted invoice PDF from HTML, ScreenshotNeo offers a website screenshot API. One GET request can return a PNG, JPEG, WebP or PDF; it is not a replacement for APITemplate.io’s invoice-template workflow. The API also has an MCP server for AI agents.

Rank #4
Brother HL-L2460DW Wireless Compact Monochrome Laser Printer with Duplex, Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • BEST FOR HOME OFFICES & SMALL TEAMS – Engineered for consistent, premium print quality, the Brother HL-L2460DW Monochrome (Black & White) Laser Printer produces documents that are clear, crisp, and easy to review and share, all at an affordable price
  • COMPACT, CONNECTED, EXCEPTIONALLY EFFICIENT– Connect with built-in dual-band wireless (2.4GHz/5GHz), Ethernet, or to a single computer via USB interface. Prints at speeds up to 36ppm(2), plus automatic duplex printing saves time and reduces paper waste
  • BROTHER MOBILE CONNECT APP – Manage your wireless printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
  • VERSATILE PAPER HANDLING – Tackle high-volume black & white printing with the 250-sheet capacity paper tray.(4) The manual feed slot enables printing on envelopes and specialty paper
  • BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer

Example Laravel request for a screenshot PDF:

$response = Http::get('https://api.screenshotneo.com/v1/shot', [
    'access_key' => config('services.screenshotneo.key'),
    'url' => 'https://example.com',
]);

$response->throw();

file_put_contents(storage_path('app/page.pdf'), $response->body());

For a PDF response, use the API’s documented output-format option for PDF; see the ScreenshotNeo API documentation for the current parameter names and options.

  • Cookie and consent banners are accepted like a visitor and removed, along with 60+ known consent platforms, newsletter popups and chat widgets; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing. Responses identify the page verdict and billing status in headers.
  • The MCP server provides take_screenshot, get_page_info and capture_pdf tools for AI agents.
  • The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I use a Blade-rendered invoice as the HTML body?

Yes. Render the invoice view in Laravel to an HTML string, then send that string as the request’s body. Make sure any CSS or assets needed for the output are available to the renderer.

Does the raw HTML endpoint return PDF bytes directly?

The documented successful response includes a download_url, along with a transaction reference and status. Validate that response and handle the URL according to your application’s needs.

Should I use the raw HTML endpoint or a saved template for every invoice?

Use raw HTML when the application already assembles the document dynamically; consider a saved template when the invoice layout is reused and should be managed separately from invoice data.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

APITemplate.ioHTML to PDFLaravelPDF generationPHP

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.