发布:2023/1/3 22:30:27作者:管理员 来源:本站 浏览次数:672
1、安装引用PuppeteerSharp
1)使用Nuget界面管理器
直接分别搜索 "PuppeteerSharp",找到对应的点安装即可。
相关文档:VS(Visual Studio)中Nuget的使用
2)使用Package Manager命令安装
PM> Install-Package PuppeteerSharp
2、使用PuppeteerSharp将URL中HTML转换PDF
Puppeteer Sharp 是官方Node.JS Puppeteer API的 .NET API,使用PuppeteerSharp将HTML转换PDF。转换代码如下,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PuppeteerSharp;
using PuppeteerSharp.Media;
namespace ConsoleApplication
{
class Program
{
public static string outputFile { get; private set; }
async static void Main(string[] args)
{
using var browserFetcher = new BrowserFetcher();
outputFile = "/home/cjavapy.pdf";
await browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
});
var page = await browser.NewPageAsync();
await page.GoToAsync("http://www.google.com");
await page.PdfAsync(outputFile, new PdfOptions
{
Format = PaperFormat.A4,
DisplayHeaderFooter = true,
MarginOptions = new MarginOptions
{
Top = "20px",
Right = "20px",
Bottom = "40px",
Left = "20px"
},
FooterTemplate = "Footer Text"
});
Console.ReadKey();
}
}
}
3、将 HTML 字符串转换为 PDF
HTML字符串也可以使用PuppeteerSharp转换为PDF。代码如下,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PuppeteerSharp;
using PuppeteerSharp.Media;
namespace ConsoleApplication
{
class Program
{
public static string outputFile { get; private set; }
async static void Main(string[] args)
{
using var browserFetcher = new BrowserFetcher();
outputFile = "/home/cjavapy.pdf";
await browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
});
//var page = await browser.NewPageAsync();
using (var page = await browser.NewPageAsync())
{
await page.SetContentAsync("www.cjavapy.com");
var result = await page.GetContentAsync();
await page.PdfAsync(outputFile, new PdfOptions
{
Format = PaperFormat.A4,
DisplayHeaderFooter = true,
MarginOptions = new MarginOptions
{
Top = "20px",
Right = "20px",
Bottom = "40px",
Left = "20px"
},
FooterTemplate = "Footer Text"
});
Console.ReadKey();
}
}
}
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4