0
点赞
收藏
分享

微信扫一扫

C# Html网页URL转PDF,列印功能(未完善)

月孛星君 2022-02-18 阅读 115

        断断续续用了很多的DLL,有好几个都没达成我想要的功能:完整的整个网页及完整的样式CSS(可能是我太菜了),有两种达成了差不多完整的效果。

        第一种:NuGet安裝Select.HtmlToPdf并引用SelectPdf  缺点:表格某些(部分)樣式丟失其他样式正常,运行结束之后在bin->Debug里面。

 using SelectPdf;

        static void Main(string[] args)
        {
            string html = @"https://www.baidu.com/";
            //第一種方法:NuGet安裝Select.HtmlToPdf并引用SelectPdf PS:表格某些樣式丟失
            HtmlToPdf toPdf = new HtmlToPdf();
            toPdf.Options.PdfPageSize = PdfPageSize.A4;//A4紙
            toPdf.Options.MarginRight = 1;//右邊距
            toPdf.Options.MarginLeft = 1;//左邊距
            toPdf.Options.WebPageWidth += 200;//調整頁面寬度
            PdfDocument pdf = toPdf.ConvertUrl(html);
            pdf.Save(new Random().Next(1, 100) + "HTML-to-PDF.pdf");//保存文件
            pdf.Close();
            Console.ReadKey();
        }

        第二种:NuGet安裝FreeSpire.PDF并引用Spire.PdfSystem.Threading、Spire.Pdf.HtmlConverter  缺点:要等20秒+(可能是我的电脑太垃圾的原因运行太慢了,不过这个比起其他方法确实要慢),说实话这个就挺好的了但是生成PDF太慢了。

using Spire.Pdf;
using Spire.Pdf.HtmlConverter;

using System.Threading;

        static void Main(string[] args)
        {
            string html = @"https://www.baidu.com/";

            //第二種方法:NuGet安裝FreeSpire.PDF并引用Spire.PdfSystem.Threading、Spire.Pdf.HtmlConverter PS:要等20m+
            PdfDocument doc = new PdfDocument();
            PdfPageSettings setting = new PdfPageSettings();//创建PdfPageSettings对象用於頁面設置
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(3);//設置頁面边距
            setting.Size = new System.Drawing.SizeF(1010, 1300);//设置页面大小
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();//创建PdfHtmlLayoutFormat对象
            htmlLayoutFormat.IsWaiting = true;//等待直至HTML内容完全加载
            Thread thread = new Thread(() =>
            {
                doc.LoadFromHTML(html, false, true, true, setting, htmlLayoutFormat);
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            doc.SaveToFile(new Random().Next(1, 100) + "HTML-to-PDF.pdf");
            doc.Close();

            Console.ReadKey();
        }

举报

相关推荐

0 条评论