C# Net Core 使用 itextsharp.lgplv2.core 把Html转PDF
阅读原文时间:2023年07月08日阅读:2

C# Net Core 使用 itextsharp.lgplv2.core 把Html转PDF

只支持英文(中文我不知道怎么弄,懂的朋友帮我看一下)!!!!!【补充:评论区的小伙伴已解决】

引入包itextsharp.lgplv2.core

代码

    public static MemoryStream Pdf(string html)  
    {  
        StringReader sr = new StringReader(html);  
        //步骤1  
        Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

        MemoryStream stream = new MemoryStream();  
        //步骤2  
        PdfWriter.GetInstance(document, stream);  
        //步骤3  
        document.Open();

        //创建一个样式表  
        StyleSheet styles = new StyleSheet();  
        ////设置默认字体的属性  
        //styles.LoadTagStyle(HtmlTags.BODY, "encoding", "Identity-H");  
        //styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONT, "Tahoma");  
        //styles.LoadTagStyle(HtmlTags.BODY, "size", "16pt");

        //FontFactory.Register(@"C:\\Windows\\Fonts\\tahoma.ttf");

        var unicodeFontProvider = FontFactoryImp.Instance;  
        unicodeFontProvider.DefaultEmbedding = BaseFont.EMBEDDED;  
        unicodeFontProvider.DefaultEncoding = BaseFont.IDENTITY\_H;

        var props = new Hashtable  
        {  
        //    { "img\_provider", new MyImageFactory() },  
            { "font\_factory", unicodeFontProvider } //始终使用Unicode字体  
        };

        //步骤4  
        //var objects = HtmlWorker.ParseToList(sr, styles, props);  
        var objects = HtmlWorker.ParseToList(sr, styles);  
        foreach (IElement element in objects)  
        {  
            document.Add(element);  
        }

        document.Close();  
        return stream;  
    }

-------------------后面补充-----------------

后面看到了这个帖子:https://dotnetcoretutorials.com/2019/07/02/creating-a-pdf-in-net-core/

中的 这段话

我决定使用包【pugpdf】:https://github.com/pug-pelle-p/pugpdf

当然如果能解决itextsharp.lgplv2.core的中文问题,我觉得他是最好的选择

-------------------后面补充-----------------

-------------------后面补充2-----------------

经过评论区的小伙伴的努力,解决了中文的问题,以下是全代码

    public static MemoryStream Pdf(string html)  
    {  
        StringReader sr = new StringReader(html);  
        //步骤1  
        Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

        MemoryStream stream = new MemoryStream();  
        //步骤2  
        PdfWriter.GetInstance(document, stream);  
        //步骤3  
        document.Open();

        //创建一个样式表  
        StyleSheet styles = new StyleSheet();  
        ////设置默认字体的属性  
        //styles.LoadTagStyle(HtmlTags.BODY, "encoding", "Identity-H");  
        //styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONT, "Tahoma");  
        //styles.LoadTagStyle(HtmlTags.BODY, "size", "16pt");

        //FontFactory.Register(@"C:\\Windows\\Fonts\\tahoma.ttf");

        var unicodeFontProvider = FontFactoryImp.Instance;  
        unicodeFontProvider.DefaultEmbedding = BaseFont.EMBEDDED;  
        unicodeFontProvider.DefaultEncoding = BaseFont.IDENTITY\_H;

        var props = new Hashtable  
        {  
        //    { "img\_provider", new MyImageFactory() },  
            { "font\_factory", unicodeFontProvider } //始终使用Unicode字体  
        };

        //步骤4  
        //var objects = HtmlWorker.ParseToList(sr, styles, props);  
        var objects = HtmlWorker.ParseToList(sr, styles);  
        foreach (IElement element in objects)  
        {  
            BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT\_EMBEDDED);  
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont);  
            Paragraph temp = element as Paragraph;  
            if (temp != null)  
            {  
                var chuck = temp\[0\] as Chunk;  
                if (chuck != null)  
                {  
                    chuck.Font = font;  
                    //document.Add(temp);  
                }  
            }  
            document.Add(element);  
        }

        document.Close();  
        return stream;  
    }

但是我发现复杂的html解析效果不是很好(相对于其他)

于是我尝试着自己来生成pdf

以下代码完成了以下功能:

*添加图片

*添加段落(文本)

*添加块到某一处(文本)

using iTextSharp.text;
using iTextSharp.text.pdf;

    public static byte\[\] CreatePdfFile()  
    {  
        using (var stream = new MemoryStream())  
        {  
            var document = new Document(PageSize.A4, 0f, 0f, 0f, 0f);

            var writer = PdfWriter.GetInstance(document, stream);  
            document.Open();

            //设置图片大小和位置  
            byte\[\] arr = Convert.FromBase64String(DataPdf.backgroundImg);  
            Image image = Image.GetInstance(arr);  
            image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);  
            image.SetAbsolutePosition(0, 0);  
            //添加图片  
            document.Add(image);

            //创建字体  
            BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT\_EMBEDDED);  
            Font font = new Font(baseFont);

            //一个段落文本  
            Paragraph paragraph = new Paragraph(@"asdas打算的!@#$%^&\*()\_  

asd

asdasdasd

                扯哦阿斯加德欧艾斯激动我按实际欧艾斯卷阿胜境的 

熬时间大厦将颠
", font);

            //添加段落  
            document.Add(paragraph);

          //添加块到列
          var ct = new ColumnText(writer.DirectContent);

          ct.SetSimpleColumn(100, 150, 500, 800, 24, Element.ALIGN_LEFT);

          var chunk = new Chunk("啥的阿萨德阿萨德as阿萨德aaaaasdasfdawswd",font);

          ct.AddElement(chunk);
          ct.Go();

            //document.NewPage();  
            //document.Add(new Phrase(""));

            //document.NewPage();  
            //writer.PageEmpty = false;

            document.Close();  
            return stream.ToArray();  
        }  
    }

学习文本(块,短语,段落)

https://www.mikesdotnetting.com/article/82/itextsharp-adding-text-with-chunks-phrases-and-paragraphs

-------------------后面补充2-----------------

块,短语和段落的文本