208人参与 • 2025-03-12 • 网页播放器
将html网页内容转换为 pdf 格式能方便文档的后续打印、存档和分享等。之前介绍过如果通过qt插件将html转为pdf文件,本文将介绍另一个新的转换方法,通过谷歌浏览器chrome插件将html网页转pdf文件。
首先需要安装spire.pdf for .net 库(10.7.21版本及以上)。可以通过此链接下载产品包后手动添加引用,或者直接通过nuget安装。
https://www.e-iceblue.cn/downloads/spire-pdf-net.html此外还需要用到谷歌浏览器插件,请确保系统中安装了chrome.exe。
c# 通过chrome插件将html网页转换为pdf文件
spire.pdf for .net新增了 chromehtmlconverter.converttopdf() 方法,支持使用 chrome 浏览器插件将 html 网页转换为 pdf。该方法中的 3 个参数为:
string input:输入 html 文件路径string output:输出 pdf 文件路径convertoptions:转换设置,可自定义设置转换超时、pdf 纸张大小和页边距等示例代码如下:
using spire.additions.chrome;
namespace converthtmltopdfusingchrome
{
internal class program
{
static void main(string[] args)
{
// 指定输入输出文档路径
string inputurl = @"https://www.e-iceblue.cn/about-us.html";
string outputfile = @"htmltopdf.pdf";
// 指定chrome插件的路径
string chromelocation = @"c:\program files\google\chrome\application\chrome.exe";
// 创建 chromehtmlconverter 对象
chromehtmlconverter converter = new chromehtmlconverter(chromelocation);
// 创建 convertoptions 对象
convertoptions options = new convertoptions();
// 设置转换超时
options.timeout = 10 * 3000;
// 设置转换后pdf页面的纸张大小和页边距
options.pagesettings = new pagesettings()
{
paperwidth = 8.27,
paperheight = 11.69,
margintop = 0,
marginleft = 0,
marginright = 0,
marginbottom = 0
};
// 将html网页转换为pdf
converter.converttopdf(inputurl, outputfile, options);
}
}
}
如果你想要在转换过程中输出日志,可以调用chromehtmlconverter.logger属性。
示例代码如下:
using spire.additions.chrome;
namespace converthtmltopdfusingchrome
{
internal class program
{
static void main(string[] args)
{
//指定输入输出文档路径
string inputurl = @"https://www.e-iceblue.cn/about-us.html";
string outputfile = @"htmltopdf.pdf";
// 指定日志文件路径
string logfilepath = @"logs.txt";
// 指定chrome插件的路径
string chromelocation = @"c:\program files\google\chrome\application\chrome.exe";
// 创建chromehtmlconverter对象
chromehtmlconverter converter = new chromehtmlconverter(chromelocation);
// 启用日志记录
converter.logger = new logger(logfilepath);
// 创建convertoptions对象
convertoptions options = new convertoptions();
// 设置转换超时
options.timeout = 10 * 3000;
// 设置转换后pdf页面的纸张大小和页边距
options.pagesettings = new pagesettings()
{
paperwidth = 8.27,
paperheight = 11.69,
margintop = 0,
marginleft = 0,
marginright = 0,
marginbottom = 0
};
// 将html网页转换为pdf
converter.converttopdf(inputurl, outputfile, options);
}
}
}
到此这篇关于c#通过chrome插件将html网页转换为pdf的文章就介绍到这了,更多相关c# chrome插件将html转pdf内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论