c# - 将带有内联 CSS 的 HTML 字符串转换为 PDF
问题描述
我有一个在 head 标签中定义了 css 的 html 文档。我希望将此 html 字符串转换为 pdf。
我使用了 ABC pdf 和 SelectPDF dll 并生成了 pdf。
当我使用 ABC pdf 时,它在转换为 pdf 时没有应用任何 CSS 样式。SelectPDF 已将 CSS 样式应用于 pdf,但有点混乱。
有谁知道如何正确地将 HTML 转换为 pdf?
解决方案
我找到了一种将具有内联样式的 HTML 字符串转换为 PDF 的解决方案。我已经使用 ABCpdf 版本 11。这个解决方案由 ABCpdf 的技术团队提供。我已经尝试了许多库和在线解决方案(我可以将我的 HTML 字符串传递给服务并获取 pdf),但没有一个给我一个好的输出,包括上述评论的解决方案。所以这里是HTML到pdf转换的解决方案。
<html>
<meta charset="utf-8" />
<head><head>
<body style="height: 100%;background-color: #D7CCC8;font-size: 12px;position: relative;height: 100%;margin: 0;">
<div style='position: relative;min-height: 100%;padding: 1em 1em 2em;margin-bottom: -11em;'>
put the content that you want to be in the pdf(with inline styling the html elements). This is an example of the html string that needs to be converted into a pdf.
</div>
</body>
</html>
以下是将上述 HTML 字符串转换为 pdf 的 C# 代码。
//generate pdf
using (Doc pdfDocument = new Doc())
{
// Set HTML options
pdfDocument.HtmlOptions.Engine = EngineType.Gecko;
pdfDocument.HtmlOptions.Media = MediaType.Screen;
// Convert first HTML page, result: html string
int pageID = pdfDocument.AddImageHtml(result);
// Convert other HTML pages
while (true)
{
if (!pdfDocument.Chainable(pageID))
{
break;
}
pdfDocument.Page = pdfDocument.AddPage();
pageID = pdfDocument.AddImageToChain(pageID);
}
//save
for (int i = 0; i < pdfDocument.PageCount; i++)
{
pdfDocument.PageNumber = i;
pdfDocument.Flatten();
}
//save the pdf, pdfFullPath: path to save the pdf
pdfDocument.Save(pdfFullPath);
}
上面的代码会将html字符串转换为pdf。注意:在我的 html 中,我没有任何图像,并且所有样式都是内联提到的,就像在示例中一样。
希望上述解决方案能像对我一样帮助某人。欢迎任何人提出对此代码的任何改进(例如:插入图像、复杂的 html 到 pdf 转换等)。
推荐阅读
- spring-boot - Vaadin 7 是否与 Spring Boot 2.x 兼容?
- python - 如何添加循环几次的所有随机生成的数字
- javascript - 试图将一串javascript文件数据转换为我可以显示的美化代码
网站上的html标签
- c# - 无重复的随机数生成器
- python-3.x - 使用 SPACY 查找匹配的公司名称
- powershell - Powershell get-adcomputer + get-wmi-object
- javascript - 当用户从 React 的下拉列表中选择一个选项时如何启用另一个输入字段
- html - 如何在 Divi Contact Form 模块提交按钮中添加 span 标签
- c# - C# Excel 互操作无法设置 PageSetup 类的 PaperSize 属性
- r - R中的3d qqplots