将 HTML 带内联 CSS 的字符串转换为 PDF

Convert HTML String With Inline CSS to PDF

我有一个 html 文档,在 head 标签中定义了 css。我希望将此 html 字符串转换为 pdf。

我使用了 ABC pdf 和 SelectPDF dll 并生成了 pdf。

当我使用 ABC pdf 时,它在转换为 pdf 时没有应用任何 CSS 样式。 SelectPDF 已将 CSS 样式应用于 pdf,但有点乱。

有人知道如何正确地将 HTML 转换为 pdf 吗?

我找到了将具有内联样式的 HTML 字符串转换为 PDF 的解决方案。我已经完成使用 ABCpdf 版本 11。此解决方案由 ABCpdf 的技术团队提供。我已经尝试了许多图书馆和在线解决方案(我可以将我的 HTML 字符串传递给服务并获取 pdf)但是 none 给了我一个很好的输出,包括上面评论的解决方案。 所以这是 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 转换等)。