Skip to content
ComPDF

HTML 转换为 PDF

这种生成 PDF 的方式,不需要模板和 JSON 数据,只需一个标准的 HTML 文件,或者标准的 HTML 字符串。

HTML 文件转为 PDF

将标准的 HTML 文件转为 PDF。下面是示例:

c#
// HTML文件路径
string htmlPath = "/htmlFile.html";
// 生成的PDF文件路径
string outputPdf = "/html2pdfOut.pdf";

// 配置属性
CConverterProperties properties = new CConverterProperties();
// 设置基础Uri
properties.SetBaseUri("/baseUri/");
// 设置页面大小
CSize pageSize = new CSize { Width = 595, Height = 842 };
properties.SetPageSize(pageSize);
// 设置字体
CFontProvider fontProvider = new CFontProvider();
fontProvider.AddDirectory("/fontDir/");
properties.SetFontProvider(fontProvider);

// 将HTML转换为PDF
CHtmlConverter.ConvertToPdf(htmlPath, outputPdf, properties);

HTML 文件流转为 PDF

将标准的 HTML 文件流转为 PDF。下面是示例:

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

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

HTML 字符串转为 PDF

将标准的 HTML 字符串转为 PDF。下面是示例:

c#
// HTML文件内容字符串
string htmlContent = @"<!DOCTYPE html> 
					<html lang=""en"">
					<body>
                        ""......""
                    </body>
                    </html>";

string outputPdf = "/html2pdfOut.pdf";

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