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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

PHP can generate a document, but it cannot directly open the print dialog on a visitor’s computer: PHP runs on your server. For a normal web application, render a print-ready page and use browser-side JavaScript to call window.print(). If you need controlled, unattended printing, send a job to a printer the server or a managed print service can access.

Choose the right kind of printing

What you need Approach
Let a visitor print a web page Printable HTML and the browser’s print dialog
A clean invoice or report A dedicated print view with print-specific CSS
Consistent pagination or a file to download and archive Generate a PDF, then let the user print it
Unattended output at an office, warehouse, or kiosk A server-side print queue, local print agent, or controlled application
Print to an arbitrary visitor’s local printer without confirmation Not something ordinary PHP or public browser code can reliably do

These are different jobs. A PHP-generated PDF does not itself print, and a server-side lpr command sends a job to a printer available to the server—not to the visitor’s printer. The distinction between browser printing and server printing was already at the heart of the original SitePoint discussion.

Print a PHP-generated page

For a typical invoice or report, PHP should load and authorize the data, render HTML, and send it to the browser. A button on that page can request the browser’s print interface. window.print() opens that interface; the user still controls printer choice, paper, copies, and other settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    http_response_code(400);
    exit('Invalid invoice ID');
}

// Load the invoice and verify that the current user is allowed to see it.
$invoice = loadAuthorizedInvoice($id);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Invoice <?= htmlspecialchars($invoice['number'], ENT_QUOTES, 'UTF-8') ?></title>
    <style>
        @page { margin: 15mm; }
        @media print {
            .no-print { display: none !important; }
            body { margin: 0; color: #000; background: #fff; }
            tr, img, .signature { break-inside: avoid; }
        }
    </style>
</head>
<body>
    <button class="no-print" type="button" onclick="window.print()">Print invoice</button>
    <main>
        <h1>Invoice <?= htmlspecialchars($invoice['number'], ENT_QUOTES, 'UTF-8') ?></h1>
        <!-- Render invoice fields and line items, escaping dynamic text. -->
    </main>
    <noscript>Use your browser’s Print command or press Ctrl/Cmd+P.</noscript>
</body>
</html>

loadAuthorizedInvoice() is an application-specific placeholder, not a built-in PHP function. Validate the requested ID and check access before rendering any document; knowing or guessing an invoice URL must not reveal another customer’s data. Escape dynamic text for HTML output rather than inserting raw values.

#1 Best Overall
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

Use a dedicated print view

A route such as /invoices/123/print is usually cleaner than asking users to print an entire dashboard. It lets you omit navigation, forms, and interactive controls; use layout rules suited to paper; and apply the same authentication and authorization checks as the regular document page. Keep a visible Print button for users who want to choose when the dialog opens.

You can also call window.print() after a dedicated print page loads. For example:

<script>
window.addEventListener('load', () => window.print());
</script>

This is a request to open the print interface, not a guarantee of silent printing. Browser policies, pop-up blocking, and kiosk configuration affect what happens. If opening a new window from a button, do so in direct response to that click, handle the case where the browser blocks the pop-up, and leave the print view accessible in the current tab as a fallback.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Canon PIXMA TS4320 – Wireless Color Inkjet Printer with Print, Copy, Scan
  • Affordable Versatility - A budget-friendly all-in-one printer perfect for both home users and hybrid workers, offering exceptional value
  • Crisp, Vibrant Prints - Experience impressive print quality for both documents and photos, thanks to its 2-cartridge hybrid ink system that delivers sharp text and vivid colors
  • Effortless Setup & Use - Get started quickly with easy setup for your smartphone or computer, so you can print, scan, and copy without delay
  • Reliable Wireless Connectivity - Enjoy stable and consistent connections with dual-band Wi-Fi (2.4GHz or 5GHz), ensuring smooth printing from anywhere in your home or office
  • Scan & Copy Handling - Utilize the device’s integrated scanner for efficient scanning and copying operations

Make the HTML work on paper

Use @media print for rules that apply only to the printed output. Hide controls and navigation, use readable type and dark text on a light background, and avoid layouts that depend on hover, screen-only content, or JavaScript that has not finished loading.

@media print {
    .screen-only, nav, .actions { display: none !important; }
    body { margin: 0; font: 11pt/1.4 Arial, sans-serif; }
    table { width: 100%; border-collapse: collapse; }
    thead { display: table-header-group; }
    tr { break-inside: avoid; }
    .page-break { break-before: page; }
}

@page can request page margins, size, or orientation, but it cannot make every physical printer print to the very edge of the paper. Printers may impose non-printable margins, and users can choose different paper, scaling, and color settings. Page-break CSS is not perfectly consistent across browsers, either.

For long tables, use a repeating header where supported and try to keep rows together. Keep totals, signatures, and other important blocks from being stranded on a separate page. Ensure images, barcodes, and fonts have loaded before printing; protected image URLs must remain accessible to the authorized user. Test long documents in the browsers, on the paper sizes, and with the printers your application actually supports.

Rank #3
Sale
Canon PIXMA TS6520 Wireless Color Inkjet Printer, Duplex Printing, Copier/Scanner, 1.42" OLED Display, Compact, White
  • Affordable Versatility - A budget-friendly all-in-one printer perfect for both home users and hybrid workers, offering exceptional value
  • Crisp, Vibrant Prints - Experience impressive print quality for both documents and photos, thanks to its 2-cartridge hybrid ink system that delivers sharp text and vivid colors
  • Effortless Setup & Use - Get started quickly with easy setup for your smartphone or computer, so you can print, scan, and copy without delay
  • Reliable Wireless Connectivity - Enjoy stable and consistent connections with dual-band Wi-Fi (2.4GHz or 5GHz), ensuring smooth printing from anywhere in your home or office
  • Scan & Copy Handling - Utilize the device’s integrated scanner for efficient scanning and copying operations

When a PDF is a better fit

HTML is often the simplest choice when users should preview a straightforward page and browser-dependent pagination is acceptable. Choose a PDF when you need defined page dimensions or a document people can download, email, archive, and print later—such as a contract, statement, formal invoice, or fixed-size label.

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

PDF does not mean identical results on every sheet of paper: printer drivers, scaling, and device margins still matter. It also does not bypass the user’s printer settings. In PHP, libraries such as Dompdf, mPDF, and TCPDF are options, not a universal ranking. HTML-to-PDF renderers and libraries that build PDFs more directly have different trade-offs. Choose based on your CSS needs, language and font requirements, page layout, barcode needs, and hosting environment, then test the actual output. Do not assume a browser stylesheet will render identically in a PDF engine.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Send a job to a server-side printer

Server-side printing fits controlled environments—such as a back office, warehouse, POS system, or kiosk—where the server or a print worker can reach the target printer. It does not print to a printer attached to an unrelated visitor’s computer. The server needs a configured printer queue, a supported file or printer language, and an operating-system account allowed to submit jobs.

On a Linux system using CUPS, a command such as lp -d Office_Printer /path/to/document.pdf can submit a PDF to a configured queue. PHP can run external programs through exec() when it is available and permitted, but do not assemble shell commands from request data. A guarded example using fixed application-controlled values is:

<?php
$pdfPath = '/srv/app/private/invoices/invoice-123.pdf';
$printer = 'Office_Printer'; // Select from a server-side allowlist.

if (!is_file($pdfPath)) {
    throw new RuntimeException('Print file does not exist.');
}

$command = sprintf(
    '/usr/bin/lp -d %s %s 2>&1',
    escapeshellarg($printer),
    escapeshellarg($pdfPath)
);

exec($command, $output, $exitCode);
if ($exitCode !== 0) {
    error_log(implode("n", $output));
    throw new RuntimeException('The print job could not be submitted.');
}

This is an example, not a portable printing API: the executable path, queue name, file format, permissions, and operating system all vary. Check whether command execution is enabled on your host, and test as the web-server account—its printer permissions may differ from your interactive shell account. The PHP manual documents exec()’s output and status behavior and warns that shell arguments need appropriate escaping.

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

For an application with real print volume or business consequences, prefer a background queue and a dedicated worker or print service over running a shell command directly during a public web request. Restrict destinations to an allowlist, record job status, and make retries deliberate: an automatic retry can print a duplicate receipt, label, or invoice. If PHP is hosted in the cloud but the printer is on a customer’s local network, a managed local agent or application is often the practical bridge. Thermal receipts and labels may require device-specific formats such as ESC/POS or ZPL rather than ordinary HTML.

Security and reliability checklist

  • Authorize access to the document before rendering, downloading, or submitting it to a printer.
  • Escape dynamic content for HTML, and keep private document files out of publicly served directories.
  • Never let a request supply an unrestricted file path, printer name, or shell command. Validate choices against server-side rules and escape shell arguments when executing a command.
  • Keep a record of server-side print jobs and their outcomes; use job identifiers to prevent accidental duplicate submissions.
  • Do not assume that a page has finished rendering just because its initial HTML loaded. Wait for required images, fonts, barcodes, and asynchronous content.
  • Test the output with the actual printer, paper size, browser, and server account involved.

Troubleshooting

Symptom Likely cause and next step
Print button does nothing Check the browser console for JavaScript errors. If a new window is involved, check pop-up blocking and offer a same-tab print view.
Images or barcodes are missing They may still be loading or require authentication. Make sure the authorized page can retrieve them and wait for required assets before requesting print.
Buttons show on paper Hide them in a print media rule, such as .no-print { display: none !important; } inside @media print.
A table row or total breaks awkwardly Try break-inside: avoid on rows or important blocks and use a repeating table header. Check the result in the target browser; pagination rules vary.
lp works in a shell but not through PHP The PHP process may run as a different operating-system user or with a different environment. Check the absolute executable path, queue permissions, and queue status as the web-server account.
exec() fails Check whether it is disabled, whether the command exists, whether the account can access the queue and file, and what exit status and output were returned.
HTML tags print as literal text The destination may be a raw-text printer rather than a browser or PDF renderer. Convert the document to a supported format or the device’s required printer language.
A PDF differs from the browser page The PDF renderer may support different CSS. Test and adjust the PDF output separately.
The same item prints twice A retry, refresh, or worker replay may have resubmitted the job. Track job status and use deliberate, auditable retries.

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.