我正在尝试使用Chrome打印到PDF来构建从HTML到PDF的转换器。选项。
我已经尝试过无头Chrome的命令行程序,但我无法添加任何设置,因此我现在尝试使用M asterDevs.ChromeDevTools
。
我的问题是每次通过await时应用程序都进入breakmode,我真的不明白问题是什么。
using System;
using MasterDevs.ChromeDevTools.Protocol.Chrome.Page;
using System.IO;
using System.Linq;
using System.Threading;
using MasterDevs.ChromeDevTools.Protocol.Chrome.DOM;
using Task = System.Threading.Tasks.Task;
using MasterDevs.ChromeDevTools;
namespace ConsoleApp4
{
internal class Program
{
const int ViewPortWidth = 1440;
const int ViewPortHeight = 900;
private static void Main(string[] args)
{
Task.Run(async () =>
{
// STEP 1 - Run Chrome
var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
using (var chromeProcess = chromeProcessFactory.Create(9222, true))
{
// STEP 2 - Create a debugging session
var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault();
var chromeSessionFactory = new ChromeSessionFactory();
var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);
// STEP 3 - Send a command
//
// Here we are sending a commands to tell chrome to set the viewport size
// and navigate to the specified URL
//await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
//{
// Width = ViewPortWidth,
// Height = ViewPortHeight,
// Scale = 1
//});
var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
{
Url = "http://www.google.com"
});
Console.WriteLine("NavigateResponse: " + navigateResponse.Id);
var printResponse = await chromeSession.SendAsync(new PrintToPDFCommand {
Landscape = true
, DisplayHeaderFooter = true
, MarginBottom = 0
, MarginTop = 0
, MarginRight = 0
, MarginLeft = 0
});
Console.WriteLine("NavigateResponse: " + navigateResponse.Id);
Console.WriteLine("Exiting ..");
}
}).Wait();
}
}
}
答案 0 :(得分:0)
好吧,让我告诉你为什么:
您没有设置纸张尺寸或比例!
然后,“ MasterDev”无法正确处理Chrome返回的后续错误。
因此,任务永远不会设置为“错误”或“成功”。
这就是为什么此时C#会无限期地等待答案的原因。
猜猜我怎么知道?
1.5年前,当我遇到相同问题时,我正在调试一个小时;)
这是错误修正提案的问题:
https://github.com/MasterDevs/ChromeDevTools/issues/37
Dim cm2inch As UnitConversion_t = Function(ByVal centimeters As Double) centimeters * 0.393701
Dim mm2inch As UnitConversion_t = Function(ByVal milimeters As Double) milimeters * 0.0393701
Dim printCommand2 As PrintToPDFCommand = New PrintToPDFCommand() With {
.Scale = 1,
.MarginTop = 0,
.MarginLeft = 0,
.MarginRight = 0,
.MarginBottom = 0,
.PrintBackground = True,
.Landscape = False,
.PaperWidth = mm2inch(conversionData.PageWidth),
.PaperHeight = mm2inch(conversionData.PageHeight) '
}
另请参阅 How to receive the height of DOM element when printing with wkhtmltopdf library?