HTML to PDF C# Overview
Easily convert HTML to PDF with a developer-friendly C# library built for speed and flexibility. Render pages exactly as they appear in the browser including HTML5, CSS3, JavaScript, responsive designs, and SPAs. Handle high volumes or real-time jobs with ease. Customize output by injecting your own JS or CSS, enabling AdBlock, hiding cookie banners, and more. Ideal for any workflow needing a reliable HTML to PDF microservice or C# library.
Lightning Fast Conversions
Process and convert files in seconds with our high-performance cloud infrastructure.
Accuracy Guaranteed
Our advanced algorithms ensure pixel-perfect and content-accurate file conversions.
Enterprise-Grade Security
ISO 27001, HIPAA, and GDPR compliant with encrypted file processing.
Global Infrastructure
Strategically located servers ensure low latency and high availability worldwide.
Developer Friendly
Comprehensive SDKs and clear documentation for quick and simple integration.
Time-Saving Automation
Automate repetitive document workflows and focus on what matters most.
Customizable Parameters
Fine-tune your automation with these powerful conversion options
File
File Supported formats: .htm .htmlFile to be converted. Value can be URL or file content.
ConversionDelay
Integer Default: 0Delay in seconds before page load and PDF creation. Sometimes useful to let web page fully load.
Range: 0 .. 30Version
Collection Default: 149Specify a particular version of the Chromium engine to render the web page.
Values: latest 149AdBlock
Bool Default: FalseBlock ads in converting page.
CookieConsentBlock
Bool Default: FalseTries to remove EU regulation required cookie warnings from web pages.
JavaScript
Bool Default: TrueAllow web pages to run JavaScript.
WaitElement
StringElement selector string of the DOM element. Converter will wait for this element to appear in DOM before conversion begins.
UserJs
StringExecute provided JavaScript before conversion begins.
UserCss
StringApply additional CSS before conversion begins.
HideElements
StringElement selector string of the DOM elements that needs to be hidden during conversion.
CssMediaType
String Default: screenUse CSS media type in conversion process. The default screen and print media types are supported but not limited to these. The custom media type, like convertapi can be used too.
Headers
StringSet custom HTTP headers to include in the request. Format: Header1:Value1|Header2:Value2|Header3:Value3
- Each header is separated by
|. - Each name/value pair is separated by
:.
LoadLazyContent
Bool Default: FalseLoad page images that loads only when they are visible.
ViewportWidth
Integer Default: 1366Sets browser viewport width.
Range: 200 .. 4000ViewportHeight
Integer Default: 1024Sets browser viewport height.
Range: 200 .. 4000Background
Bool Default: TrueConvert web page background.
FixedElements
Collection Default: fixedChange fixed elements CSS 'position' property to adapt page for conversion.
Values: fixed absolute relative hideShowElements
StringElement selector string of the DOM elements that should be visible during conversion. Other elements will be hidden.
AvoidBreakElements
StringCSS selector for the elements that pages should not break.
BreakBeforeElements
StringCSS selector for the elements that should apply page break before it.
BreakAfterElements
StringCSS selector for the elements that should apply page break after it.
AuthUsername
StringHTTP authentication username. Could be used if conversion web page is protected with HTTP authentication.
AuthPassword
StringHTTP authentication password. Could be used if conversion web page is protected with HTTP authentication.
Cookies
StringSet additional cookies for the page request. Example: cookiename1=cookievalue1; cookiename2=cookievalue2; cookiename3=cookievalue3
RespectViewport
Bool Default: TrueIf true, the converter will generate PDF as the content looks like in the browser. If is set to false, the converter acts like Chrome print to PDF function.
Scale
Integer Default: 100Set web page scale value in percentage.
Range: 10 .. 200PageOrientation
Collection Default: portraitPDF page orientation.
Values: portrait landscapePageSize
Collection Default: letterPDF page size.
Values: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 b0 b1 b2 b3 b4 b5 letter legal ledgerMarginTop
Integer Default: 10Set the page top margin in millimeters (mm).
Range: 0 .. 500MarginRight
Integer Default: 10Set the page right margin in millimeters (mm).
Range: 0 .. 500MarginBottom
Integer Default: 10Set the page bottom margin in millimeters (mm).
Range: 0 .. 500MarginLeft
Integer Default: 10Set the page left margin in millimeters (mm).
Range: 0 .. 500Header
StringThis property will insert an HTML header into each page. HTML tags containing the classes pageNumber, totalPages, title, and date will be filled in with the metadata relevant to each individual page. Inline CSS could be utilized to style the HTML provided.
<style>
.right {
float: right;
}
.left {
float: left;
}
</style>
<span class='left'>
page number
<span class='pageNumber'></span>
</span>
<span class='right'>
date
<span class='date'></span>
</span>
Footer
StringThis property will insert an HTML footer into each page. HTML tags containing the classes pageNumber, totalPages, title, and date will be filled in with the metadata relevant to each individual page. Inline CSS could be utilized to style the HTML provided.
<style>
.right {
float: right;
}
.left {
float: left;
}
</style>
<span class='left'>
page number
<span class='pageNumber'></span>
</span>
<span class='right'>
date
<span class='date'></span>
</span>
PageWidth
IntegerCustom page width in millimeters (mm). This option override PageSize option.
Range: 10 .. 30000PageHeight
IntegerCustom page height in millimeters (mm). This option override PageSize option.
Range: 10 .. 30000PageRange
String Default: 1-100Set page range. Example 1-10 or 1,2,5.
StoreFile
Bool Default: FalseWhen the StoreFile parameter is set to True, your converted file is written to ConvertAPI’s encrypted, temporary storage and made available via a time-limited secure download URL, valid for up to 3 hours. After this period, the file is permanently deleted.
When StoreFile is set to False, conversion happens entirely in-memory. The raw file bytes are streamed back in the API response without touching disk or external storage, ensuring maximum security and zero persistence so that only you can access the content.
Step-by-Step Guide
Easy HTML to PDF integration programmatically using our simple C# SDK
1. C# library install
ConvertAPI provides an ASP.NET C# library that allows you to perform a HTML to PDF conversion with just a few lines of code. Convert HTML to PDF using C# programming language with no effort at all!
Install-Package ConvertApi
2. Authenticate ConvertAPI C# library
You can obtain your API Token by signing up for a free account. Once you sign up, you'll receive 250 free conversions instantly! Grab your authentication key from the account dashboard, and authenticate the ConvertAPI C# library like this:
ConvertApi convertApi = new ConvertApi("api_token");
3. HTML to PDF using C# .NET
Once you have your authentication in place, simply copy-paste this HTML to PDF conversion code snippet into your C# project:
Advanced C# SDK Techniques
Take your ConvertAPI C# integrations to the next level with advanced techniques for real-world, production-grade document conversion workflows.
These advanced patterns help you build robust, scalable, and efficient HTML to PDF pipelines in your .NET applications while maintaining flexibility and control over your document workflows.
Convert a Remote HTML File
The following C# example demonstrates how to convert a HTML file hosted online (accessible via a public URL) directly to PDF using ConvertAPI. This is useful when your documents are already stored on cloud storage (S3, Azure Blob, etc.) and you want to convert them without downloading locally first.
In this example:
- No local download needed before conversion.
- The HTML file is fetched from the provided URL.
- ConvertAPI converts it to PDF and saves it to a temporary folder on your server or local machine.
- Ideal for server-side processing pipelines and automated workflows.
var convertApi = new ConvertApi("api_key");
var sourceFile = new Uri("https://cdn.convertapi.com/public/files/demo.html");
Console.WriteLine($"Converting online {sourceFile} document to PDF...");
var htmlToPdfResult = await convertApi.ConvertAsync("html", "pdf", new ConvertApiFileParam(sourceFile));
var outputFileName = htmlToPdfResult.Files[0];
var fileInfo = await outputFileName.SaveFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName));
Console.WriteLine("The PDF result saved to " + fileInfo);
Convert a HTML File Stream to PDF and Receive a File Stream
This C# example demonstrates how to convert a HTML file provided as a stream directly to PDF using ConvertAPI and receive the converted PDF as a stream without writing to disk. This is ideal for in-memory processing in ASP.NET APIs, serverless functions, or pipeline services where you need to handle documents securely and efficiently.
In this example:
- You pass a HTML file stream (html_stream) with a filename hint to ConvertAPI.
- ConvertAPI converts the document to PDF without saving intermediate files.
- The converted PDF is returned as a stream (outputStream) for direct processing, returning to clients, or further manipulation in your pipeline.
- Ideal for secure, diskless document conversion workflows.
var conversionResult = await convertApi.ConvertAsync("html", "pdf",
new ConvertApiFileParam(html_stream, "test.html")
);
var outputStream = await conversionResult.Files.First().FileStreamAsync();
Console.Write(new StreamReader(outputStream).ReadToEnd());
Console.WriteLine("End of file stream.");
Handling Exceptions During HTML to PDF Conversion
This C# example shows how to handle exceptions when converting a HTML file to PDF using ConvertAPI. By catching ConvertApiException, you can access detailed error information, making it easier to debug issues such as invalid API tokens, unsupported file formats, or conversion errors in your workflow.
In this example:
- A try-catch block safely wraps the HTML to PDF conversion.
- If the API call fails, ConvertApiException provides the HTTP status code and API response details for clear diagnostics.
- This approach ensures your application can handle errors gracefully, log issues, and respond with meaningful messages to users or calling services.
try
{
var convertApi = new ConvertApi("api_token");
const string sourceFile = @"..\..\..\TestFiles\test.html";
var convert = await convertApi.ConvertAsync("html", "pdf",
new ConvertApiFileParam(sourceFile));
}
//Catch exceptions and write details
catch (ConvertApiException e)
{
Console.WriteLine("Status Code: " + e.StatusCode);
Console.WriteLine("Response: " + e.Response);
}
Integrate within minutes
Easy HTML to PDF automation using our simple C# SDK
Compatible With All .NET Frameworks & Tools
Frequently Asked Questions
What is ConvertAPI C# SDK?
The ConvertAPI C# SDK is a lightweight, easy-to-use library for .NET developers to integrate document and file conversions into their applications with minimal code. It connects directly to the ConvertAPI REST service, allowing you to automate file conversions, merging, splitting, and more.
What types of conversions are supported?
ConvertAPI offers 300+ converters and tools, including DOCX to PDF, XLSX to PDF, PDF to JPG, HTML to PDF, image processing, metadata extraction, compression, and advanced document workflows. You can automate complex document processing scenarios within your .NET applications using the SDK.
Can I build complex conversion workflows using the SDK?
Yes, the ConvertAPI .NET C# SDK allows you to chain conversions, merge documents, extract pages, and apply advanced parameters to automate end-to-end document workflows within your applications.
Is there a file size limit when using ConvertAPI?
The maximum file size you can convert depends on your ConvertAPI plan type. Higher-tier plans allow larger files and increased concurrency for high-volume document processing needs.
Can I convert files entirely in memory without storing them on your servers?
Yes, ConvertAPI supports in-memory conversions, allowing you to send and receive files as streams without saving them to disk on ConvertAPI servers. This enables secure, diskless workflows for sensitive or temporary files.
Which .NET versions does the ConvertAPI SDK support?
The SDK supports .NET Framework 4.5+, .NET Core, .NET 5, 6, 7, and 8, ensuring compatibility across your existing and new projects.
Businesses trust us
Highest rated File Conversion API on major B2B software listing platforms: Capterra, G2, and Trustpilot.
"ConvertAPI has been a game-changer for our document automation workflows. Their conversion accuracy and API reliability are unmatched in the industry for over 7 years."
"ConvertAPI is a reliable, cost-effective solution with a proven track record of stability. It has grown significantly in maturity, adopting enterprise-grade practices over the years."
"We've integrated ConvertAPI across our entire document processing platform. The performance is exceptional and the support team is always responsive. Highly recommended!"
Enterprise-Grade Security
We ensure that all document processing is handled securely in the cloud, adhering to industry-leading standards like ISO 27001, GDPR, and HIPAA. To enhance security even further, we can ensure that no files or data are stored on our servers and never leave your country.
Learn more about security