基于 HTML 代码生成 PDF(iTextSharp、PDFSharp?)

发布于 2024-12-07 11:27:57 字数 845 浏览 0 评论 0原文

PDFSharp 库是否可以像 iTextSharp 一样生成 PDF 文件*考虑 HTML 格式*? (粗体(strong)、间距(br)等)

之前我用过iTextSharp,大致是这样处理的(代码如下):

 string encodingMetaTag = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
 string htmlCode = "text <div> <b> bold </ b> or <u> underlined </ u> <div/>";

 var sr = new StringReader (encodingMetaTag + htmlCode);
 var pdfDoc = new Document (PageSize.A4, 10f, 10f, 10f, 0f);
 var = new HTMLWorker htmlparser (pdfDoc);
 PdfWriter.GetInstance (pdfDoc, HttpContext.Current.Response.OutputStream);
 pdfDoc.Open ();
 htmlparser.Parse (sr);
 pdfDoc.Close ();

合并到合适的HTML表单到PDF文档中处理类对象 HTMLWorker.. 那么 PDFSharp 又如何呢? PDFSharp有类似的解决方案吗?

Does the library PDFSharp can - like iTextSharp - generate PDF files *take into account HTML formatting *? (bold (strong), spacing (br), etc.)

Previously I used iTextSharp and roughly handled in such a way (code below):

 string encodingMetaTag = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
 string htmlCode = "text <div> <b> bold </ b> or <u> underlined </ u> <div/>";

 var sr = new StringReader (encodingMetaTag + htmlCode);
 var pdfDoc = new Document (PageSize.A4, 10f, 10f, 10f, 0f);
 var = new HTMLWorker htmlparser (pdfDoc);
 PdfWriter.GetInstance (pdfDoc, HttpContext.Current.Response.OutputStream);
 pdfDoc.Open ();
 htmlparser.Parse (sr);
 pdfDoc.Close ();

incorporated into the appropriate HTML form to a PDF document dealt with the class object HTMLWorker.. so what with PDFSharp? Has PDFSharp similar solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

稀香 2024-12-14 11:27:58

使用 PdfSharp 的 PDF HTML 渲染器 可以从 HTML 生成 PDF

  1. 作为图像,或
  2. 作为文本

在插入 PDF 之前

。要渲染为图像,请参考迭戈答案中的代码。

要呈现为文本,请参考以下代码:

static void Main(string[] args)
{
    string html = File.ReadAllText(@"C:\Temp\Test.html");
    PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
    pdf.Save(@"C:\Temp\Test.pdf");
}

public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
    var imgObj = Image.FromFile(@"C:\Temp\Test.png");
    e.Callback(XImage.FromGdiPlusImage(imgObj));    
}

public static void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
{
    e.SetStyleSheet = @"h1, h2, h3 { color: navy; font-weight:normal; }";
}

HTML 代码

<html>
    <head>
        <title></title>
        <link rel="Stylesheet" href="StyleSheet" />      
    </head>
    <body>
        <h1>Images
            <img src="ImageIcon" />
        </h1>
    </body>
</html>

HTML Renderer for PDF using PdfSharp can generate a PDF from an HTML

  1. as an image, or
  2. as text

before inserting to the PDF.

To render as an image, please refer to the code from Diego answer.

To render as text, please refer code below:

static void Main(string[] args)
{
    string html = File.ReadAllText(@"C:\Temp\Test.html");
    PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
    pdf.Save(@"C:\Temp\Test.pdf");
}

public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
    var imgObj = Image.FromFile(@"C:\Temp\Test.png");
    e.Callback(XImage.FromGdiPlusImage(imgObj));    
}

public static void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
{
    e.SetStyleSheet = @"h1, h2, h3 { color: navy; font-weight:normal; }";
}

HTML code

<html>
    <head>
        <title></title>
        <link rel="Stylesheet" href="StyleSheet" />      
    </head>
    <body>
        <h1>Images
            <img src="ImageIcon" />
        </h1>
    </body>
</html>
归途 2024-12-14 11:27:58

不幸的是,HtmlRenderer 不是一个适合在基于 .NET 5.0 的项目中使用的库:

System.IO.FileLoadException: 'Could not load file or assembly 'HtmlRenderer,
Version=1.5.0.6, Culture=neutral, PublicKeyToken=null'. The located assembly's 
manifest definition does not match the assembly reference. (0x80131040)'

另外,我发现依赖包 HtmlRender.PdfSharp 有以下警告消息:

Package 'HtmlRenderer.PdfSharp 1.5.0.6' was restored using 
'.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, 
.NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, 
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project 
target framework 'net5.0'. This package may not be fully compatible with your project.

顺便说一句,我设法使用另一个库将 HTML 渲染为 PDF :

License.LicenseKey = "license key";
var renderer = new ChromePdfRenderer();
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync(youtHtml);
pdf.SaveAs("your html as pdf.pdf");

IronPDF License.LicenseKey 不是必需的,您可以将其删除,但您的 pdf 将在每页末尾生成带有 IronPDF 水印的 PDF。但 IronPDF 提供获取试用许可证密钥

Unfortunately, HtmlRenderer is not an appropriate library to be used in a project based on .NET 5.0:

System.IO.FileLoadException: 'Could not load file or assembly 'HtmlRenderer,
Version=1.5.0.6, Culture=neutral, PublicKeyToken=null'. The located assembly's 
manifest definition does not match the assembly reference. (0x80131040)'

Also, I found that the dependency package HtmlRender.PdfSharp has the following warning message:

Package 'HtmlRenderer.PdfSharp 1.5.0.6' was restored using 
'.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, 
.NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, 
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project 
target framework 'net5.0'. This package may not be fully compatible with your project.

By the way, I managed to render HTML as PDF using another library IronPDF:

License.LicenseKey = "license key";
var renderer = new ChromePdfRenderer();
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync(youtHtml);
pdf.SaveAs("your html as pdf.pdf");

The line with License.LicenseKey is not necessary and you can remove it, but your pdf will be generated with the IronPDF watermark in the end of each page. But IronPDF provides getting trial license key.

叹沉浮 2024-12-14 11:27:58

经过长时间的斗争,我成功使用 Polybioz.HtmlRenderer.PdfSharp.Core

=> HtmlRenderer.PdfSharp.Core 是 HtmlRenderer.PdfSharp for .NET Core 的部分移植

它在 Net5.0 中工作:)

我的解决方案直接受到 VDWWD 和其他人的启发,

          PdfPage page = new PdfPage();
        PdfOutline outline = new PdfOutline();

        page = document.AddPage();
        XGraphics gfx_ = XGraphics.FromPdfPage(page);
        using (var container = new HtmlContainer())
        {
            var pageSize = new XSize(page.Width, page.Height);

            var x = 5;
            var y = 100;


            container.Location = new XPoint(x, y);
            container.MaxSize = pageSize;
            container.PageSize = pageSize;


                        const string latinstuff =
            "Facin exeraessisit la consenim iureet dignibh eu <b>facilluptat</b> vercil dunt autpat. " +
            "Ecte magna faccum dolor sequisc iliquat, quat, quipiss equipit accummy niate magna " +
            "facil iure eraesequis am velit, quat atis dolore dolent luptat nulla adio odipissectet " +
            "lan venis do essequatio conulla facillandrem <u>zzriusci</u> bla ad minim inis nim velit eugait " +
            "aut aut lor at ilit ut nulla ate te eugait alit augiamet ad magnim iurem il eu feuissi.\n" +
            "Guer sequis duis eu feugait luptat lum adiamet, si tate dolore mod eu facidunt adignisl in " +
            "henim dolorem nulla faccum vel inis dolutpatum iusto od min ex euis adio exer sed del " +
            "dolor ing enit veniamcon vullutat praestrud molenis ciduisim doloborem ipit nulla consequisi.\n" +
            "Nos adit pratetu eriurem delestie del ut lumsandreet nis exerilisit wis nos alit venit praestrud " +
            "dolor sum volore facidui blaor erillaortis ad ea augue corem dunt nis  iustinciduis euisi.\n" +
            "Ut ulputate volore min ut nulpute dolobor sequism olorperilit autatie modit wisl illuptat dolore " +
            "min ut in ute doloboreet ip ex et am dunt at.";


            //container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");
            string text = "This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br>" +
                $"<br><a href=\"http://www.google.nl\">www.google.nl</a>{DateTime.Now.ToLongTimeString()}";
            text +=  latinstuff;
            text += "<p style=\"text-align:center;\">" + latinstuff  + "</p>";                
            text += "<p style=\"text-align:justify;\">" + latinstuff + "</p>";
            text += "<div width=\"70mm\" style=\"text-align:justify;\"><p>" + latinstuff + "</p></div>";

            container.SetHtml(text);

            using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
            {
                container.PerformLayout(measure);
            }

            gfx_.IntersectClip(new XRect(0, 0, page.Width + 400, page.Height));
            container.PerformLayout(gfx_);
            container.PerformPaint(gfx_);
        }

唯一剩下的想法是拉丁语中未呈现粗体(“facilluptat”应加粗),请参阅我的 打印页面屏幕

after a long struggle, i succeed using Polybioz.HtmlRenderer.PdfSharp.Core

=> HtmlRenderer.PdfSharp.Core is a partial port of HtmlRenderer.PdfSharp for .NET Core

it work in Net5.0 :)

my solution, directly inspired from VDWWD and others

          PdfPage page = new PdfPage();
        PdfOutline outline = new PdfOutline();

        page = document.AddPage();
        XGraphics gfx_ = XGraphics.FromPdfPage(page);
        using (var container = new HtmlContainer())
        {
            var pageSize = new XSize(page.Width, page.Height);

            var x = 5;
            var y = 100;


            container.Location = new XPoint(x, y);
            container.MaxSize = pageSize;
            container.PageSize = pageSize;


                        const string latinstuff =
            "Facin exeraessisit la consenim iureet dignibh eu <b>facilluptat</b> vercil dunt autpat. " +
            "Ecte magna faccum dolor sequisc iliquat, quat, quipiss equipit accummy niate magna " +
            "facil iure eraesequis am velit, quat atis dolore dolent luptat nulla adio odipissectet " +
            "lan venis do essequatio conulla facillandrem <u>zzriusci</u> bla ad minim inis nim velit eugait " +
            "aut aut lor at ilit ut nulla ate te eugait alit augiamet ad magnim iurem il eu feuissi.\n" +
            "Guer sequis duis eu feugait luptat lum adiamet, si tate dolore mod eu facidunt adignisl in " +
            "henim dolorem nulla faccum vel inis dolutpatum iusto od min ex euis adio exer sed del " +
            "dolor ing enit veniamcon vullutat praestrud molenis ciduisim doloborem ipit nulla consequisi.\n" +
            "Nos adit pratetu eriurem delestie del ut lumsandreet nis exerilisit wis nos alit venit praestrud " +
            "dolor sum volore facidui blaor erillaortis ad ea augue corem dunt nis  iustinciduis euisi.\n" +
            "Ut ulputate volore min ut nulpute dolobor sequism olorperilit autatie modit wisl illuptat dolore " +
            "min ut in ute doloboreet ip ex et am dunt at.";


            //container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");
            string text = "This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br>" +
                
quot;<br><a href=\"http://www.google.nl\">www.google.nl</a>{DateTime.Now.ToLongTimeString()}";
            text +=  latinstuff;
            text += "<p style=\"text-align:center;\">" + latinstuff  + "</p>";                
            text += "<p style=\"text-align:justify;\">" + latinstuff + "</p>";
            text += "<div width=\"70mm\" style=\"text-align:justify;\"><p>" + latinstuff + "</p></div>";

            container.SetHtml(text);

            using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
            {
                container.PerformLayout(measure);
            }

            gfx_.IntersectClip(new XRect(0, 0, page.Width + 400, page.Height));
            container.PerformLayout(gfx_);
            container.PerformPaint(gfx_);
        }

the only think which is remain is that the bold is not rendered (the "facilluptat" should be bolded) in the latinstuff, see my print screen of the page

栖迟 2024-12-14 11:27:58

我会推荐您NReco.PdfGenerator,因为它有免费和付费许可证,并且很容易从 nuget 安装。

主页:https://www.nrecosite.com/pdf_generator_net.aspx

文档:https://www.nrecosite.com/doc/NReco.PdfGenerator/

如果您想从 html 文件创建 PDF,请尝试:

String html = File.ReadAllText("main.html");
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.GeneratePdf(html, null, "C:/Users/Tmp/Desktop/mapa.pdf");

I'll recommend you NReco.PdfGenerator because have free and paid license and its easy to install from nuget.

Main page: https://www.nrecosite.com/pdf_generator_net.aspx

Documentation: https://www.nrecosite.com/doc/NReco.PdfGenerator/

If you want create PDF from html file try:

String html = File.ReadAllText("main.html");
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.GeneratePdf(html, null, "C:/Users/Tmp/Desktop/mapa.pdf");
荒岛晴空 2024-12-14 11:27:57

我知道这个问题已经很老了,但这里有一个干净的方法...

您可以使用 HtmlRenderer 与 PDFSharp 结合来完成此操作:

Bitmap bitmap = new Bitmap(1200, 1800);
Graphics g = Graphics.FromImage(bitmap);
HtmlRenderer.HtmlContainer c = new HtmlRenderer.HtmlContainer();
c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
c.PerformPaint(g);
PdfDocument doc = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
xgr.DrawImage(img, 0, 0);
doc.Save(@"C:\test.pdf");
doc.Close();
        

有些人报告最终图像看起来有点模糊,显然到期的自动抗锯齿。以下是有关如何解决此问题的帖子消息:http: //forum.pdfsharp.com/viewtopic.php?f=2&t=1811&start=0

I know this question is old, but here's a clean way to do it...

You can use HtmlRenderer combined with PDFSharp to accomplish this:

Bitmap bitmap = new Bitmap(1200, 1800);
Graphics g = Graphics.FromImage(bitmap);
HtmlRenderer.HtmlContainer c = new HtmlRenderer.HtmlContainer();
c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
c.PerformPaint(g);
PdfDocument doc = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
xgr.DrawImage(img, 0, 0);
doc.Save(@"C:\test.pdf");
doc.Close();
        

Some people report that the final image looks a bit blurry, apparently due to automatic anti-aliasing. Here's a post message on how to fix that: http://forum.pdfsharp.com/viewtopic.php?f=2&t=1811&start=0

洋洋洒洒 2024-12-14 11:27:57

不,PDFsharp 当前不包含解析 HTML 文件的代码。

No, PDFsharp does not currently include code to parse HTML files.

要走干脆点 2024-12-14 11:27:57

老问题,但以上都不适合我。然后我尝试了 HtmlRenderergeneratepdf 方法与 pdfsharp。希望有帮助:
您必须安装名为 HtmlRenderer.pdfsharp 的 nuget。

var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("Your html in a string",PageSize.A4);
  PdfPage page = new PdfPage();
  XImage img = XImage.FromGdiPlusImage(bitmap);
  doc.Pages.Add(page);
  XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
  xgr.DrawImage(img, 0, 0);
  doc.Save(Server.MapPath("test.pdf"));
  doc.Close();

Old question but none of above worked for me. Then i tried generatepdf method of HtmlRenderer in combination of pdfsharp. Hope it helps:
You must install a nuget named HtmlRenderer.pdfsharp.

var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("Your html in a string",PageSize.A4);
  PdfPage page = new PdfPage();
  XImage img = XImage.FromGdiPlusImage(bitmap);
  doc.Pages.Add(page);
  XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
  xgr.DrawImage(img, 0, 0);
  doc.Save(Server.MapPath("test.pdf"));
  doc.Close();
苏别ゝ 2024-12-14 11:27:57

如果您只想将某个 HTML 字符串写入 PDF,而不希望将其余字符串写入 PDF,则可以使用 TheArtOfDev HtmlRenderer。此代码片段使用 V 1.5.1

using PdfSharp.Pdf;
using PdfSharp;
using PdfSharp.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;

//create a pdf document
using (PdfDocument doc = new PdfDocument())
{
    doc.Info.Title = "StackOverflow Demo PDF";

    //add a page
    PdfPage page = doc.AddPage();
    page.Size = PageSize.A4;

    //fonts and styles
    XFont font = new XFont("Arial", 10, XFontStyle.Regular);
    XSolidBrush brush = new XSolidBrush(XColor.FromArgb(0, 0, 0));

    using (XGraphics gfx = XGraphics.FromPdfPage(page))
    {
        //write a normal string
        gfx.DrawString("A normal string written to the PDF.", font, brush, new XRect(15, 15, page.Width, page.Height), XStringFormats.TopLeft);

        //write the html string to the pdf
        using (var container = new HtmlContainer())
        {
            var pageSize = new XSize(page.Width, page.Height);

            container.Location = new XPoint(15,  45);
            container.MaxSize = pageSize;
            container.PageSize = pageSize;
            container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");

            using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
            {
                container.PerformLayout(measure);
            }

            gfx.IntersectClip(new XRect(0, 0, page.Width, page.Height));

            container.PerformPaint(gfx);
        }
    }

    //write the pdf to a byte array to serve as download, attach to an email etc.
    byte[] bin;
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, false);
        bin = stream.ToArray();
    }
}

If you only want a certain HTML string written to the PDF but not the rest, you can use the HtmlContainer from TheArtOfDev HtmlRenderer. This snippet uses V 1.5.1

using PdfSharp.Pdf;
using PdfSharp;
using PdfSharp.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;

//create a pdf document
using (PdfDocument doc = new PdfDocument())
{
    doc.Info.Title = "StackOverflow Demo PDF";

    //add a page
    PdfPage page = doc.AddPage();
    page.Size = PageSize.A4;

    //fonts and styles
    XFont font = new XFont("Arial", 10, XFontStyle.Regular);
    XSolidBrush brush = new XSolidBrush(XColor.FromArgb(0, 0, 0));

    using (XGraphics gfx = XGraphics.FromPdfPage(page))
    {
        //write a normal string
        gfx.DrawString("A normal string written to the PDF.", font, brush, new XRect(15, 15, page.Width, page.Height), XStringFormats.TopLeft);

        //write the html string to the pdf
        using (var container = new HtmlContainer())
        {
            var pageSize = new XSize(page.Width, page.Height);

            container.Location = new XPoint(15,  45);
            container.MaxSize = pageSize;
            container.PageSize = pageSize;
            container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");

            using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
            {
                container.PerformLayout(measure);
            }

            gfx.IntersectClip(new XRect(0, 0, page.Width, page.Height));

            container.PerformPaint(gfx);
        }
    }

    //write the pdf to a byte array to serve as download, attach to an email etc.
    byte[] bin;
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, false);
        bin = stream.ToArray();
    }
}
¢好甜 2024-12-14 11:27:57

在我去年开发的一个项目中,我使用 wkhtmltopdf (http://wkhtmltopdf.org/) 从 html 生成 pdf然后我读取该文件并将其返回给用户。

它对我来说效果很好,对你来说可能是一个主意......

In a project that I developed last year I used wkhtmltopdf (http://wkhtmltopdf.org/) to generate pdf from html then I read the file and get back it to the user.

It works fine for me and it could be an idea for you...

猛虎独行 2024-12-14 11:27:57

你们听说过这个吗?我可能回复得很晚,但我认为这有帮助。它非常简单并且效果很好。

var htmlContent = String.Format("<body>Hello world: {0}</body>", 
        DateTime.Now);
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);

编辑:我带着使用“PDFSharp”将 HTML 代码转换为 PDF 的问题来到这里,发现“PDFSharp”无法做到这一点,然后我发现了 NReco,它对我有用,所以我觉得它可能会帮助像我这样的人。

Have you guys heard of this. I might be answering very late but I thought it helps. It is very simple and works well.

var htmlContent = String.Format("<body>Hello world: {0}</body>", 
        DateTime.Now);
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);

Edit: I came here with the question of converting HTML code to PDF using 'PDFSharp' and found out that 'PDFSharp' cannot do it then I found out about NReco and it worked for me so I felt it might help someone just like me.

木格 2024-12-14 11:27:57

我知道这是一个非常老的问题,但我意识到没有人说实际上有一种准确的方法可以将 HTML 渲染为 PDF。根据我的测试,我发现您需要以下代码才能成功完成此操作。

Bitmap bitmap = new Bitmap(790, 1800);
Graphics g = Graphics.FromImage(bitmap);
XGraphics xg = XGraphics.FromGraphics(g, new XSize(bitmap.Width, bitmap.Height));
TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
c.SetHtml("Your html in a string here");

PdfDocument pdf = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
pdf.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(pdf.Pages[0]);
c.PerformLayout(xgr);
c.PerformPaint(xgr);
xgr.DrawImage(img, 0, 0);
pdf.Save("test.pdf");

还有另一种方法可以做到,但您可能会遇到尺寸问题。

PdfDocument pdf = PdfGenerator.GeneratePdf(text, PageSize.A4);
pdf.Save("test.pdf");

I know there is a really old question but I realize that there is no one saying actually an accurate method to render an HTML into a PDF. Based on my test I found out that you need the following code to successfully do it.

Bitmap bitmap = new Bitmap(790, 1800);
Graphics g = Graphics.FromImage(bitmap);
XGraphics xg = XGraphics.FromGraphics(g, new XSize(bitmap.Width, bitmap.Height));
TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
c.SetHtml("Your html in a string here");

PdfDocument pdf = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
pdf.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(pdf.Pages[0]);
c.PerformLayout(xgr);
c.PerformPaint(xgr);
xgr.DrawImage(img, 0, 0);
pdf.Save("test.pdf");

There is another way to do but you might have problems with the size.

PdfDocument pdf = PdfGenerator.GeneratePdf(text, PageSize.A4);
pdf.Save("test.pdf");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文