Skip to content
ComPDF

Convert HTML to PDF

This method of generating PDF does not require templates or JSON data. It only needs a standard HTML file or a standard HTML string.

Convert HTML File to PDF

Convert standard HTML file to PDF. Below is an example:

csharp
// HTML file path
string htmlPath = "/htmlFile.html";
// Generated PDF file path
string outputPdf = "/html2pdfOut.pdf";

// Configure properties
CConverterProperties properties = new CConverterProperties();
// Set base Uri
properties.SetBaseUri("/baseUri/");
// Set page size
CSize pageSize = new CSize { Width = 595, Height = 842 };
properties.SetPageSize(pageSize);
// Set font
CFontProvider fontProvider = new CFontProvider();
fontProvider.AddDirectory("/fontDir/");
properties.SetFontProvider(fontProvider);

// Convert HTML to PDF
CHtmlConverter.ConvertToPdf(htmlPath, outputPdf, properties);

Convert HTML File Stream to PDF

Convert a standard HTML file stream to PDF. The following is an example:

csharp
string htmlPath = "/htmlFile.html";
string outputPdf = "/html2pdfOut.pdf";

FileStream htmlStream = File.OpenRead(htmlPath);
FileStream outputPdfStream = File.Create(outputPdf);
CHtmlConverter.ConvertToPdf(htmlStream, outputPdfStream);

Convert HTML String to PDF

Convert a standard HTML string to PDF. The following is an example:

csharp
// HTML content string
string htmlContent = @"<!DOCTYPE html> 
					<html lang=""en"">
					<body>
                        ""......""
                    </body>
                    </html>";

string outputPdf = "/html2pdfOut.pdf";

FileStream outputPdfStream = File.Create(outputPdf);
CHtmlConverter.ConvertToPdf(htmlContent, outputPdfStream);