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
ASP.NET MVC

How to Convert Secured ASP.NET MVC Pages to PDF with wkhtmltopdf

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

To convert an authenticated ASP.NET MVC page, wkhtmltopdf must receive the same valid authentication state as a browser. For Forms Authentication, obtain a current authentication cookie, pass it with --cookie (or a cookie jar), request the protected HTTPS URL, and stream the generated PDF from a server-side action. If the cookie is missing, expired, scoped to another host or rejected, wkhtmltopdf follows the normal redirect and captures the login page instead.

The reliable conversion pattern

A secure implementation has four parts:

  1. An authorized MVC action accepts a record identifier, not an arbitrary URL.
  2. The action builds the destination URL from trusted configuration.
  3. wkhtmltopdf receives a short-lived Forms Authentication cookie and any required headers.
  4. The action validates the process result, returns application/pdf, and deletes temporary files.

Forms Authentication is cookie-based. An unauthenticated request is redirected with HTTP 302 to the login page. After successful authentication, the server issues an authentication cookie that must accompany subsequent requests. wkhtmltopdf does not perform an ASP.NET form login automatically; it renders whatever response it receives.

Why a protected page becomes a login-page PDF

The usual causes are authentication-state problems rather than PDF problems:

  • No authentication cookie was supplied.
  • The cookie expired before conversion or belongs to a different application.
  • The cookie domain or path does not match the target URL.
  • The request uses HTTP while the application requires HTTPS.
  • The page redirects to a different host, where the cookie is not valid.
  • Cookies or headers reach the main document but not protected CSS, images or scripts.

Check the final URL and response path with a normal browser first. A valid browser session is evidence that the application works, but the renderer still needs its own cookie or cookie jar.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
  • Convert your PDF files into Word, Excel & Co. the easy way
  • Convert scanned documents thanks to our new 2022 OCR technology
  • Adjustable conversion settings
  • No subscription! Lifetime license!
  • Compatible with Windows 11, 10, 8.1, 7 - Internet connection required

Design the MVC endpoint safely

Accept an identifier, not a URL

Use an action such as /Reports/Invoice/42 and look up record 42 after authorization. Do not let a caller submit an arbitrary URL for the renderer. Otherwise the PDF feature can become a server-side request forgery path into internal services.

Keep the destination on HTTPS

Forms Authentication credentials and tickets must be protected with TLS. Use an HTTPS base URL from application configuration and reject a missing or non-HTTPS value in production.

Use a dedicated rendering identity

A short-lived service session or a narrowly scoped user session limits what the renderer can read. Never place a real cookie, password or bearer token in source control, command examples, permanent files or ordinary logs.

wkhtmltopdf options that matter for authentication

Option Purpose When to use it
--cookie name value Sends one cookie; the option can be repeated. Pass the Forms Authentication ticket and any other required cookies.
--cookie-jar path Reads or writes a cookie jar. Use when a login flow or several cookies must be retained.
--custom-header name value Adds an HTTP header. Supply a required tenant, correlation or authorization header.
--custom-header-propagation Propagates custom headers to subresource requests. Useful when protected CSS, images or scripts require the same header.
--username and --password HTTP authentication credentials. Only for HTTP Basic or similar server authentication, not ASP.NET form posts.
--enable-javascript Runs page JavaScript. Enable when the document is assembled in the browser.
--javascript-delay milliseconds Waits after loading before capture. Allow a bounded time for asynchronous data and charts.
--load-error-handling abort|skip|ignore Controls load failures. Choose deliberately; abort prevents silently returning an incomplete PDF.

The library API exposes equivalent settings such as load.cookieJar, load.username, load.password, load.jsdelay, load.customHeaders, load.post and load.loadErrorHandling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
  • Convert over 50 document file formats.
  • Preview your files from Doxillion before converting them.
  • Use batch conversion to convert thousands of files at once.
  • Enjoy an easy-to-use, intuitive interface with a Drag and Drop file option.
  • Burn your converted or original files directly to disc.

Pass a Forms Authentication cookie from the command line

For an application using the default cookie name, a command has this shape. Replace the value with a current, short-lived ticket; do not hard-code a production credential.

wkhtmltopdf 
  --cookie .ASPXAUTH "SHORT_LIVED_COOKIE_VALUE" 
  --custom-header-propagation 
  --enable-javascript 
  --javascript-delay 500 
  --load-error-handling abort 
  https://app.example.test/Reports/Invoice/42 
  invoice-42.pdf

If the application changed its cookie name, use that configured name instead of .ASPXAUTH. To use a jar:

wkhtmltopdf 
  --cookie-jar /secure temporary path/render.cookies 
  --enable-javascript 
  --load-error-handling abort 
  https://app.example.test/Reports/Invoice/42 
  invoice-42.pdf

Ensure the process account can read the jar and that the file is removed immediately after conversion. A jar is not a substitute for authentication: it must contain a valid cookie for the target host and path.

Complete ASP.NET MVC example

The following .NET Framework MVC pattern reuses the authenticated request’s Forms Authentication cookie. It builds the target from a trusted base URL, imposes a timeout and returns a PDF only after a successful exit code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

public class ReportsController : Controller
{
    [Authorize]
    public ActionResult InvoicePdf(int id)
    {
        if (id <= 0) return new HttpStatusCodeResult(400);

        var baseUrl = ConfigurationManager.AppSettings["PublicBaseUrl"];
        var executable = ConfigurationManager.AppSettings["WkhtmltopdfPath"];
        if (String.IsNullOrWhiteSpace(baseUrl) || !baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            return new HttpStatusCodeResult(500, "An HTTPS rendering URL is not configured.");

        var target = new Uri(new Uri(baseUrl.TrimEnd('/') + "/"), "Reports/Invoice/" + id);
        var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || String.IsNullOrEmpty(authCookie.Value))
            return new HttpStatusCodeResult(401, "The rendering session is not authenticated.");

        var folder = Path.Combine(Path.GetTempPath(), "pdf-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(folder);
        var output = Path.Combine(folder, "document.pdf");

        try
        {
            var arguments = String.Join(" ", new[]
            {
                "--cookie", Quote(FormsAuthentication.FormsCookieName), Quote(authCookie.Value),
                "--custom-header-propagation",
                "--enable-javascript",
                "--javascript-delay", "500",
                "--load-error-handling", "abort",
                Quote(target.AbsoluteUri), Quote(output)
            });

            var start = new ProcessStartInfo
            {
                FileName = executable,
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardError = true
            };

            using (var process = Process.Start(start))
            {
                if (process == null || !process.WaitForExit(90000))
                {
                    if (process != null && !process.HasExited) process.Kill();
                    return new HttpStatusCodeResult(504, "PDF rendering timed out.");
                }

                var error = process.StandardError.ReadToEnd();
                if (process.ExitCode != 0 || !System.IO.File.Exists(output))
                {
                    // Send error details to a protected diagnostic sink, never to a public response.
                    return new HttpStatusCodeResult(502, "The PDF renderer failed.");
                }
            }

            var bytes = System.IO.File.ReadAllBytes(output);
            return File(bytes, "application/pdf", "invoice-" + id + ".pdf");
        }
        finally
        {
            try { Directory.Delete(folder, true); } catch { /* clean up asynchronously if required */ }
        }
    }

    private static string Quote(string value)
    {
        return """ + value.Replace("\", "\\").Replace(""", "\"") + """;
    }
}

Configure PublicBaseUrl and WkhtmltopdfPath outside source control. The example intentionally does not write the cookie or renderer stderr to a normal log. In a production implementation, send sanitized diagnostics to an access-controlled sink and consider an isolated worker process for untrusted page content.

Make protected subresources render

A page can return correctly while its images, stylesheets or scripts fail. Inspect each secured resource’s host and path. The authentication cookie must be valid for that origin, and a custom header may need propagation. If a resource is on another domain, a cookie scoped to the application domain will not be sent there; use an explicit, narrowly scoped server-to-server credential only when that service supports it.

Keep images enabled unless you deliberately want a text-only document. If the page fills content through JavaScript, enable JavaScript and choose the shortest delay that consistently allows the data to settle. A delay is not a synchronization guarantee, so a server-rendered or deterministic readiness marker is preferable where you control the page.

Forms Authentication is not HTTP Basic Authentication

--username and --password implement HTTP authentication challenged by the web server. They do not submit an ASP.NET login form and do not create a Forms Authentication ticket. For Forms Authentication, authenticate separately, capture the resulting cookie, and pass it with --cookie or a cookie jar. If your application uses Basic Authentication at the server boundary, use the username and password flags instead of pretending they are an MVC session.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

Choose failure behavior intentionally

Use abort when an incomplete document is unacceptable, such as invoices or legal records. skip can be appropriate when one failed resource should not cancel the whole document, and ignore is the most permissive choice. Record the exit status and a sanitized error classification. Do not return a successful PDF merely because a file was created; verify the process result and expected output.

Security checklist

  • Require authorization on the PDF action and re-check record ownership before rendering.
  • Construct URLs from trusted configuration; never accept a caller-supplied destination.
  • Use HTTPS for login, the protected page and authenticated resources.
  • Use short-lived, least-privilege rendering sessions.
  • Protect temporary directories and delete cookie jars and PDFs after use.
  • Scrub cookies, passwords, authorization headers and full query strings from logs.
  • Apply process, memory and network egress limits to the renderer.
  • Set a finite conversion timeout and terminate stuck processes.
  • Keep the wkhtmltopdf binary updated according to your platform’s package and security policy.

Troubleshooting by symptom

Symptom Likely cause Fix
The PDF is the login page. Cookie missing, expired, incorrectly named, out of scope or rejected over HTTP. Capture a fresh cookie, use the configured cookie name, verify host/path and use the HTTPS URL.
Main HTML is present but CSS or images are absent. Subresources need cookies or headers that were not sent. Check each resource origin, cookie scope and --custom-header-propagation.
Dynamic areas are blank. JavaScript is disabled or the capture occurs before asynchronous work completes. Enable JavaScript and add a bounded delay; prefer a deterministic readiness condition when possible.
Renderer exits non-zero. A navigation or resource failed, or the selected error mode aborted. Inspect protected stderr diagnostics, then decide whether abort, skip or ignore matches the document’s integrity requirements.
Cookie works in a browser but not in the process. The browser has additional cookies, a different host, a redirect, or a client-specific header. Trace the complete redirect chain, export all required cookies, and reproduce required headers without logging their values.
Conversion hangs. Network request, JavaScript or a resource never completes. Set a process timeout, use bounded JavaScript delay, limit network access and terminate the child process safely.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and operating cost

wkhtmltopdf runs a browser engine for each conversion, so rendering time depends on page size, images, JavaScript and network latency. No responsible benchmark is established here; measure your own pages with representative authentication and concurrency. Reuse only what is safe: a process-level queue can control load, but do not share one user’s cookie across unrelated jobs.

For predictable output, render from an internal endpoint close to the application, keep assets cacheable where policy allows, avoid unbounded third-party requests and make the page expose all required data in its initial response. Treat a timeout or missing resource as a job failure when document completeness matters. Your operating cost is the compute, storage, monitoring and maintenance of the renderer and its isolated runtime; the command-line tool itself is open source under the LGPLv3 according to its official project description.

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot and PDF API with an MCP server for Claude, Cursor and other MCP clients. It can use cookies, custom headers and authorization settings for protected pages, wait for selectors or network idle, run JavaScript, capture full pages and return PDF output without you maintaining a browser process. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and each response identifies the page verdict and billing status in headers.

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.

The documented one-call shape is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://app.example.test/Reports/Invoice/42 -o shot.webp

For PDF output and the cookie or header settings needed by your application, use the options in the ScreenshotNeo documentation. The service also provides take_screenshot, get_page_info and capture_pdf MCP tools, custom CSS and JavaScript, device and viewport controls, async jobs with signed webhooks, bulk capture for up to 100 URLs per call, caching with a chosen TTL, signed links and a usage API. Every feature is on every plan: 1,000 shots per month are free with no card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it without a card.

Best Value
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
  • ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
  • MAXIMUM FUNCIONALITY – create interactive forms, compare PDFs, bates numbering, find and replace text or colors, convert documents, OCR engine, comment, highlight, fill out and print forms, document protection and others
  • EASY TO INSTALL AND USE – well-structured user-interface, in-program instructions, free tech support whenever you need it
  • GREAT VALUE FOR MONEY - why spend a fortune if you can have maximum functionality at a reasonable price - this also fits the requirements of companies very well

Frequently Asked Questions

Can one authentication cookie be reused for multiple PDF jobs?

Only while it remains valid and its scope matches every target. Prefer short-lived, least-privilege sessions and renew them rather than distributing a long-lived user ticket.

What should a renderer do when a protected asset is on another host?

A cookie for the MVC host will not automatically authenticate a different origin. Configure that service’s supported server-to-server credential separately and keep its scope narrow.

Is a successful wkhtmltopdf exit proof that the document is complete?

No. Validate the exit code, output file and required page content, and select an error mode that matches how strictly your workflow treats missing resources.

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

Quick Recap

Bestseller No. 1
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
Convert your PDF files into Word, Excel & Co. the easy way; Convert scanned documents thanks to our new 2022 OCR technology
$29.99
Bestseller No. 2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Convert over 50 document file formats.; Preview your files from Doxillion before converting them.
Bestseller No. 3
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 4
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$99.99
Bestseller No. 5
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
$29.99

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 *

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

Read next

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.