当前位置: 移动技术网 > IT编程>开发语言>c# > C#:采用TuesPechkin生成Pdf

C#:采用TuesPechkin生成Pdf

2020年04月17日  | 移动技术网IT编程  | 我要评论

1、需求

前段时间有个需求,要求把网页生成pdf,找了各种插件,才决定使用这个tuespechkin,这个是后台采用c#代码进行生成

2、做法

我要做的是一个比较简单的页面,采用mvc绑定,数据动态加载,页面上给个按钮,点击后请求后台接口,便可以生成pdf文件了

3、实现方式

引入两个相关dll,tuespechkin.wkhtmltox.xxx  根据你当前的系统来选择对应的dll(一般添加前两个就行),

 

4、生成pdf代码段

先在后台将指定html页生成为string字符串,然后调用如下方法即可

        /// <summary>
        /// 生成pdf
        /// </summary>
        /// <param name="htmlstr">生成内容</param>
        /// <param name="path">生成地址</param>
        private static void converthtmltexttopdf(string htmlstr, string filepath)
        {
            if (!directory.exists(filepath))  //不存在文件夹,创建
                directory.createdirectory(filepath);  //创建新的文件夹

            var filename = datetime.now.tostring("yyyymmddhhmmssffff") + ".pdf";
            var path = filepath + filename;
            var document = new htmltopdfdocument
            {
                globalsettings =
                {
                    produceoutline = true,
                    documenttitle = "标题",
                    papersize = paperkind.a4, // implicit conversion to pechkinpapersize
                    margins =
                    {
                        all=0,
                        unit = unit.centimeters
                    }
                },
                objects =
                {
                    new objectsettings
                    {
                        htmltext =htmlstr,
                        websettings =new websettings
                        {
                            defaultencoding="utf-8",
                            loadimages=true,
                        }
                    }
                },
            };


            byte[] buf = getconverter().convert(document);
            //直接把result二进制数据写入文件流
            filestream fs = new filestream(path, filemode.openorcreate);
            fs.write(buf, 0, buf.length);
            fs.close();
            itoolset toolset = new pdftoolset();
            toolset.unload();  
        }

 5、备注

此插件对css样式支持比较友好,但是不支持使用外部样式表,必须为嵌入样式,而且生成出来的pdf整体版面偏小,需要微调样式,细心一点

6、最后来一张效果图

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网