首页 > 解决方案 > 将带有内联 CSS 的 HTML 字符串转换为 PDF

问题描述

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

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

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

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

标签: c#asp.net-mvchtml-to-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 转换等)。


推荐阅读