ScreenshotNeo

BlogHow-to

How to Capture Indian Government Portal Pages as PDF with PHP

Generate PDFs from Indian government portals with PHP using headless Chrome or Dompdf, then check A4 layout, fonts, and page completeness.

By the ScreenshotNeo team4 October 202610 min read

Short answer: If the portal relies on JavaScript or modern browser layout, control Chrome or Chromium from PHP and print the rendered page to PDF. For static HTML with simple CSS, Dompdf can be a lighter PHP-native option. The right choice depends on the specific portal, so inspect the output for missing content, A4 pagination, fonts, and images.

A PDF capture is a derivative copy, not proof that a page or document is official. Preserve the portal URL and context, and check the target site’s access rules before automating. For official guidance, see the Guidelines for Indian Government Websites and Apps (GIGW), which covers government websites and applications across central, state, and local levels.

1. Choose the renderer for the page

Page characteristics Starting point Trade-off
JavaScript-rendered content, interactive components, or modern browser CSS PHP-controlled Chrome/Chromium with chrome-php/chrome Uses a real browser, so it requires a browser binary and process execution on the host.
Static HTML and modest layout requirements Dompdf PHP-native rendering, but its documented CSS support is narrower than a browser; flexbox and grid are not supported.
Login, CAPTCHA, consent, or other access controls Review the specific portal’s policy and permitted workflow first There is no universal automation rule for every Indian government portal.

The chrome-php/chrome project documentation describes controlling Chrome/Chromium and producing PDFs from PHP. It currently lists PHP 7.4–8.5 and Chrome/Chromium 65 or newer; verify the requirements for the release you install. The Dompdf documentation describes a PHP HTML-to-PDF renderer with mostly CSS 2.1 support. These project capabilities do not establish that a particular portal will render correctly.

2. Capture a rendered page with PHP and Chrome

Install the library with Composer and make a compatible Chrome or Chromium binary available to the PHP process. This example navigates to a page, waits for navigation, requests A4 output, and saves the PDF. Replace the example URL with a page you are permitted to access.

composer require chrome-php/chrome
<?php
require __DIR__ . '/vendor/autoload.php';

use HeadlessChromium\BrowserFactory;

$url = 'https://example.gov.in/';
$outputPath = __DIR__ . '/portal-page.pdf';

$browserFactory = new BrowserFactory();
$browser = $browserFactory->createBrowser();

try {
    $page = $browser->createPage();
    $page->navigate($url)->waitForNavigation();

    // If the page has a known content marker, wait for it before printing.
    // Replace this selector with one that exists on the target portal.
    // $page->waitForXPath('//main');

    $page->pdf([
        'paperWidth' => 8.27,   // A4 width in inches
        'paperHeight' => 11.7,  // A4 height in inches
        'marginTop' => 0.4,
        'marginBottom' => 0.4,
        'marginLeft' => 0.4,
        'marginRight' => 0.4,
        'printBackground' => true,
        'landscape' => false,
        'displayHeaderFooter' => false,
    ])->saveToFile($outputPath);

    if (!is_file($outputPath) || filesize($outputPath) === 0) {
        throw new RuntimeException('PDF output was not created.');
    }

    echo "Saved PDF to {$outputPath}" . PHP_EOL;
} finally {
    $browser->close();
}

The library’s API and accepted PDF options can vary by installed release; consult its documentation if a method signature differs. In a web endpoint, do not let a request parameter select arbitrary URLs to visit. Restrict capture targets to trusted destinations to avoid turning the service into a way to access internal network resources.

Choose waits based on actual page content

A navigation event does not prove that every delayed widget, table, chart, or language-specific section has appeared. Prefer waiting for a meaningful selector when the library and page make that possible. If content appears after a known client-side action, wait for that state before printing. Avoid relying on a short fixed sleep as the only readiness check: it may be too short on a slow response and waste time on a fast one.

Set page geometry deliberately

GIGW includes a checkpoint that page content should print correctly on A4 paper. Start with A4 dimensions, then inspect the actual output. For wide tables, try landscape orientation or a suitable scale and check that columns are not clipped. Adjust margins for the portal’s content and any browser-generated header or footer. Printing backgrounds can preserve colored sections, but may increase file size and may not be necessary for a readable record.

3. Render static HTML with Dompdf

Dompdf is suitable when you already have the HTML to render, the page is static, and its CSS fits the renderer’s documented support. It does not execute a page in a browser, so passing a portal URL as HTML will not reproduce JavaScript-driven page state. A basic Composer-based example:

composer require dompdf/dompdf
<?php
require __DIR__ . '/vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$html = '<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: sans-serif; font-size: 12px; }
    h1 { font-size: 20px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #777; padding: 5px; }
  </style>
</head>
<body>
  <h1>Portal record</h1>
  <p>Render trusted, prepared HTML here.</p>
</body>
</html>';

$options = new Options();
$options->set('isRemoteEnabled', false);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
file_put_contents(__DIR__ . '/portal-page.pdf', $dompdf->output());

Use setPaper('A4', 'landscape') for a wide page if that is more legible. The example disables remote resource loading because remote access should be an intentional decision. Dompdf documents that remote resources require remote loading to be enabled and cURL or allow_url_fopen; local files must remain within configured chroot paths. Do not enable broad access just to make an asset appear: limit what the renderer can fetch and validate input HTML.

4. Handle government portal details and edge cases

  • Indian-language text: Check Hindi and any other Indic scripts in the generated PDF. Dompdf’s built-in fonts do not cover every character; its documentation says characters outside Windows ANSI encoding coverage need an external font. Make the required font available to the renderer and verify the output glyph by glyph.
  • Remote images and logos: Confirm they loaded before capture. For Dompdf, remote loading must be enabled for remote assets; for a browser capture, asset failures can still leave blank spaces.
  • Long pages and tables: Inspect page breaks, repeated table headings, rows split across pages, and clipped columns. A4 portrait is not automatically suitable for every layout.
  • Lazy-loaded content: Scroll or otherwise trigger the relevant content before printing if the site only loads it as it enters view. Verify the last sections are present.
  • Authentication and session state: A server-side capture may see a sign-in page instead of the intended content. Use only a permitted authentication flow and protect credentials and session cookies.
  • CAPTCHAs and consent prompts: Do not assume they may be bypassed. Check the target portal’s terms and access flow. The National Government Services Portal policy cited here is specific to that portal and does not establish a rule for other sites.
  • Accessibility: Keep an accessible HTML page or official downloadable document available when one exists. GIGW recommends accessible document formats and an accessible version of scanned documents; its accessibility guidance calls for OCR text in scanned PDFs. A visual capture may not preserve semantic structure or selectable text.
  • Official context: Record the source URL and capture date alongside the PDF where appropriate. A PDF alone does not establish authenticity or current validity.

See the GIGW guidelines for the official context on print presentation and accessibility, and consult the specific portal’s own policy. The NGSP policy’s instruction about opening pages in a newly opened browser window applies to NGSP; do not generalize it to every department site.

5. Verify the PDF before relying on it

  1. Open the PDF and compare its key sections with the portal page in a browser.
  2. Check that the expected page title, tables, notices, date fields, images, and lower-page content are present.
  3. Print or preview at A4 size. Look for clipped edges, tiny text, awkward page breaks, or a table extending past the page.
  4. Select and copy Indic-language text where possible; inspect for missing glyphs or substitutions.
  5. Check whether links and text remain usable, and whether a scanned or image-only result needs OCR to make its text accessible.
  6. Retain the official source and its context if the PDF is used as a record.

6. Troubleshooting

Symptom Likely cause What to check or change
Chrome fails to start Browser binary missing, incompatible, or unavailable to the PHP process Install a supported Chrome/Chromium build, confirm the runtime versions against the library release, and check that the web process can execute it.
PDF is blank or shows a loading screen Capture happened before client-rendered content appeared, or the site returned an access screen Wait for a meaningful page element, inspect the browser state, and confirm permitted access and session state.
Some rows or sections are missing Delayed, paginated, or lazy-loaded content was not present at print time Trigger the required page state, wait for the target content, and verify the complete page before capture.
Layout differs from the browser view Dompdf lacks browser layout features such as flexbox/grid, or print styles alter the page Use Chrome/Chromium for browser-dependent layout, or simplify the HTML/CSS for Dompdf. Inspect print-specific behavior.
Indic characters appear as boxes or disappear Font coverage or embedding problem Use a font with the needed script coverage and ensure it is available to the renderer; check the saved PDF, not just the source HTML.
Images are missing in Dompdf Remote loading is disabled, URL access is unavailable, or local path is outside chroot Prefer controlled local assets where appropriate; otherwise configure narrowly scoped resource access and confirm cURL or allow_url_fopen availability.
Table columns are cut off Page is too wide for portrait A4 at the current scale and margins Try landscape, revise margins or print styles, and inspect a physical-size preview.
PDF has no selectable text Output is image-based, or source content was already scanned Use an accessible source format where available; for scanned documents, OCR may be needed. Verify the resulting text for accuracy.
Request hangs or times out Portal response, scripts, or remote assets are slow or blocked Set an application-level time limit appropriate to your environment, log which stage stalls, and avoid unbounded retries. No universal timeout guarantees success across portals.

7. Performance, reliability, and cost

A headless browser runs a full browser process, so account for process startup, memory, browser lifecycle, and concurrent jobs in your PHP deployment. Reuse or isolate browser processes according to the library’s documented lifecycle and your application’s security model; always close resources after capture. Dompdf avoids running a browser but may require layout compromises and resource fetching still affects completion time.

Portal speed, scripts, authentication, and remote assets can vary. For repeated captures, use bounded timeouts, log the target and failure stage without recording secrets, and retry only transient failures with a limit. This research contains no measured success rate, timing, or load behavior for repeated capture, so evaluate the actual portal and deployment. Costs depend on your hosting and operational setup; the cited project documentation does not provide a universal cost estimate.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. For a PDF from PHP, request the PDF output using the documented API options and save the response. The API supports PDF settings including paper size, margins, landscape, and page ranges; see the ScreenshotNeo API documentation for current parameter names and response handling.

<?php
$endpoint = 'https://api.screenshotneo.com/v1/shot';
$params = [
    'access_key' => 'YOUR_API_KEY',
    'url' => 'https://example.gov.in/',
    'format' => 'pdf',
    'paper' => 'A4',
];

$ch = curl_init($endpoint . '?' . http_build_query($params));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 90,
]);
$data = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($data === false || $status < 200 || $status >= 300) {
    throw new RuntimeException('ScreenshotNeo request failed: ' . ($error ?: 'HTTP ' . $status));
}
file_put_contents(__DIR__ . '/portal-page.pdf', $data);

ScreenshotNeo accepts consent banners as a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks/CAPTCHAs, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Portal-specific access rules still apply. Sign up for 1,000 free screenshots a month with no card.

FAQ

Can PHP create a PDF without installing Chrome?

Yes. Dompdf can render prepared HTML in PHP, but it does not execute portal JavaScript and has a narrower CSS feature set.

Should I use A4 portrait for every portal?

Use A4 as the starting point for this context, then inspect the result. Wide tables may need landscape orientation or adjusted print styles.

Does a captured PDF prove that a government page is authentic?

No. It is a derivative capture. Keep the official source URL and context, and follow the portal’s own policy.

Will the same setup work on every Indian government portal?

No single result can be assumed across sites. Pages differ in rendering, content loading, access controls, fonts, and policy; validate each target.

Are scanned PDFs accessible by default?

No. GIGW guidance calls for OCR text in scanned PDFs. Check whether the document has usable text and retain an accessible source when one is available.