Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk7 min

PDFCrowd PHP API Example: Convert WordPress HTML to PDF

A practical WordPress handler pattern for converting authorized HTML to a PDF with PDFCrowd’s PHP client, returning it as a download, and choosing between string, URL, and file inputs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To generate a PDF download from WordPress content with PDFCrowd, render the authorized content into an HTML string on the server, pass it to PDFCrowd’s PHP client with convertString(), then return the resulting bytes with the application/pdf content type. Put the conversion in a server-side WordPress handler, verify the request nonce, and separately check that the user may access the specific content.

Install the PDFCrowd PHP client

Install the client in the project that contains your site-specific plugin or its Composer-managed dependencies:

composer require pdfcrowd/pdfcrowd

The client class used by the PHP examples is PdfcrowdHtmlToPdfClient. Keep the PDFCrowd username and API key in private server-side configuration; do not put them in page markup, source control, or values supplied by a visitor.

Add a WordPress download form

A basic file download does not need AJAX. A form can submit to admin-post.php, where WordPress dispatches the request to a registered admin_post_... action for a logged-in user.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
    <input type="hidden" name="action" value="my_site_pdf">
    <input type="hidden" name="report_id" value="<?php echo esc_attr($report_id); ?>">
    <?php wp_nonce_field('my_site_pdf'); ?>
    <button type="submit">Download PDF</button>
</form>

Use this form only where the user is entitled to request the selected report. Escape values when rendering them, and validate the report identifier again in the handler rather than trusting the submitted field.

Convert rendered WordPress HTML and return the PDF

This illustrative plugin pattern combines documented PDFCrowd client methods with WordPress conventions. It is not a vendor-published or tested plugin. Replace the report lookup, capability, HTML template, configuration access, and error handling with the rules for your site.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
<?php
// In a site-specific plugin; load Composer's autoloader as appropriate for your project.
add_action('admin_post_my_site_pdf', 'my_site_pdf_handler');

function my_site_pdf_handler() {
    check_admin_referer('my_site_pdf');

    $report_id = isset($_POST['report_id'])
        ? absint(wp_unslash($_POST['report_id']))
        : 0;

    // Placeholder only: use the least-privilege capability and check access
    // to this particular report or record.
    if (! current_user_can('read') || ! my_site_user_can_view_report($report_id)) {
        wp_die('You are not allowed to generate this PDF.', '', ['response' => 403]);
    }

    $report = my_site_get_report($report_id);
    if (! $report) {
        wp_die('Report not found.', '', ['response' => 404]);
    }

    // Escape dynamic values for their HTML context. Use a trusted template
    // if the document has more than a small amount of markup.
    $title = esc_html($report->title);
    $body = wp_kses_post($report->body);
    $html = '<!doctype html><html><head><meta charset="utf-8">'
        . '<title>' . $title . '</title></head><body>'
        . '<h1>' . $title . '</h1>' . $body
        . '</body></html>';

    try {
        $client = new \Pdfcrowd\HtmlToPdfClient(
            PDFCrowd_USERNAME_FROM_PRIVATE_CONFIG,
            PDFCrowd_API_KEY_FROM_PRIVATE_CONFIG
        );
        $pdf = $client->convertString($html);

        nocache_headers();
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="report.pdf"');
        echo $pdf;
        exit;
    } catch (\Pdfcrowd\Error $error) {
        error_log('PDFCrowd conversion failed: ' . $error);
        wp_die('PDF generation failed. Please try again later.', '', ['response' => 502]);
    }
}

my_site_user_can_view_report(), my_site_get_report(), and the two configuration constants above represent application-specific code; define them before using the pattern. The handler must run before theme output or stray whitespace is sent, or the PDF response can be corrupted by HTML preceding the binary bytes. In a production plugin, use an error and logging strategy appropriate to the sensitivity of the document.

Nonce validation is not authorization

check_admin_referer() verifies request intent, not permission to retrieve a document. WordPress Developer Resources explicitly cautions: “Nonces should never be relied on for authentication, authorization, or access control.” Check the current user’s capability and their access to the specific record independently; choose a more restrictive capability than read where the application requires it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Choose the right PDFCrowd input method

Input PHP methods Use it when Important consideration
Rendered HTML string convertString() returns PDF bytes; convertStringToFile() writes a file WordPress has already assembled the document HTML, including content that is private or not publicly reachable. Ensure referenced images, fonts, and styles are available to the conversion process; a string alone does not embed external assets.
URL convertUrl() returns bytes; convertUrlToFile() saves a file The page is accessible to PDFCrowd’s conversion servers and rendering the URL produces the intended document. PDFCrowd must be able to reach the page and its required assets. A local or access-controlled WordPress page may not be reachable.
Local HTML file or asset archive convertFileToFile() You need to upload a local document together with its assets and save the resulting PDF to a server file. For an archive containing multiple HTML files, set the documented option that identifies the main file.

For a WordPress-rendered document, the string route is usually the most direct because it avoids asking a remote converter to fetch a private page. Use a URL when remote reachability is appropriate and useful. For local assets, make them reachable through absolute URLs or an appropriate base URL, or package the HTML and assets into an archive and use the file conversion route.

Configure the document before conversion

The PHP guide lists configuration methods for options such as page size, margins, headers and footers, scaling, print media, custom CSS, JavaScript readiness, and selecting an element. Apply the relevant settings to the client before calling the conversion method; for example, setPageSize(), setPageMargins(), setCustomCss(), and setWaitForElement() are documented method names. Consult the current PHP guide for accepted values and method signatures rather than guessing parameter formats.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

These settings matter when the browser view is not the desired print output. A report may need print-specific CSS, a wait condition for content rendered by JavaScript, or selection of a single element instead of the whole page. Test the result with the actual template and assets used by the handler before relying on it for important documents.

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

Return bytes or write a PDF file

convertString() and convertUrl() return PDF bytes in PHP memory. This is convenient for a direct download, as in the handler above. The corresponding convertStringToFile(), convertUrlToFile(), and convertFileToFile() methods write output to a file, which can suit workflows that retain or process the result on the server. Choose deliberately: an in-memory response needs enough PHP memory for the returned PDF, while a file workflow needs suitable storage, cleanup, and access controls. The PDFCrowd guide documents the conversion methods; it does not establish performance figures for a particular WordPress host or document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Troubleshoot common failures

  • The response is an HTML error page, not a PDF: Check that the handler sends no theme output or whitespace before the PDF bytes, that the response headers are set before output, and that the conversion exception is caught. Use server logs for the underlying error rather than exposing credentials or internal details to visitors.
  • PDFCrowd cannot load a URL: The conversion service must reach the page and its referenced resources. Use a rendered string or uploaded file/archive for private or locally available content, or make the required resources accessible through appropriate URLs.
  • The PDF omits styles, images, or other assets: Check the asset URLs and base URL from the converter’s point of view. For local assets, use accessible absolute URLs or package them with the HTML in an archive.
  • JavaScript-generated content is missing: Configure an appropriate readiness condition, such as the documented element-wait option, before conversion; ensure the selector represents content that actually appears.
  • A user can request a document they should not see: A valid nonce does not establish authorization. Check capability and access to the specific report or record in the handler before building its HTML.
  • The client reports a conversion or validation error: PDFCrowd’s PHP guide says the client throws PdfcrowdError for conversion or validation errors. Catch that exception, log it through the site’s chosen logging path, and return a valid WordPress error response instead of beginning a PDF response.

Or skip the browser setup

ScreenshotNeo is for producing website screenshots, not PDFCrowd-style HTML-to-PDF conversion. If your adjacent task is to capture a web page as an image, its API takes a URL in one GET request; see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Before the shot, ScreenshotNeo accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server gives AI agents screenshot, page-info, and PDF-capture tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan.

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.

Leave a Reply

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

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.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.