How to get html content and convert it to PDF with itextsharp?

How to get html content and convert it to PDF with itextsharp?

傾城如夢未必闌珊 发布于 2021-11-24 字数 492 浏览 740 回复 2 原文

Does anyone know how to get a html content, convert it to pdf and save it to database?

I've tried so many ways, but nothing seems to work. In some articles, it's written to use HTMLParse, in others HTMLWorker... sometimes throws an error "document has no pages"... sometimes, it just throws an exception but it didn't specify the error...

Does anyone know a good way to do this?

I'm using C# 3.0, ASP.NET MVC and LinQToSQL.

Thanks in advance and a lot!!

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



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


久隐师 2022-06-07 2 楼
 public class Pdf : IPdf
        public FileStreamResult Make(string s)
            using (var ms = new MemoryStream())
                using (var document = new Document())
                    PdfWriter.GetInstance(document, ms);
                    using (var str = new StringReader(s))

                        var htmlWorker = new HTMLWorker(document);


                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);

                return new FileStreamResult(HttpContext.Current.Response.OutputStream, "application/pdf");
傲鸠 2022-06-07 1 楼

For HTML to PDF i tend to look at HTMLDoc. It's an exe and not a library, so it may not be exactly what you are looking for, but it'll probably get you over the hump.

Looking at the iText book, Lowagie says:

"One of the frequent questions on the iText mailing list is, 'Does iText provide HTML2PDF functionality?' The official answer is no; you're advised to use HtmlDoc or ICEBrowser." Page 456.

He then goes on to show an example of HTMLParser, but stresses it's not up to the huge job of parsing and presenting HTML.