如果没有纯代码解决方案,也许有一些方法可以连接到“Microsoft Print to PDF”选项?
是的,但是使用这种方式,您需要首先在RichEditBox或TextBlock等控件中显示您的HTML字符串,只有UIElement可以是可打印的内容。
您也可以自己创建 PDF 文件,这里是 PDF 中使用的基本语法:
您可以使用BT 和ET 来创建段落:
这是 C# 中的示例:
StringBuilder sb = new StringBuilder();
sb.AppendLine("BT"); // BT = begin text object, with text-units the same as userspace-units
sb.AppendLine("/F0 40 Tf"); // Tf = start using the named font "F0" with size "40"
sb.AppendLine("40 TL"); // TL = set line height to "40"
sb.AppendLine("230.0 400.0 Td"); // Td = position text point at coordinates "230.0", "400.0"
sb.AppendLine("(Hello World)'");
sb.AppendLine("/F2 20 Tf");
sb.AppendLine("20 TL");
sb.AppendLine("0.0 0.2 1.0 rg"); // rg = set fill color to RGB("0.0", "0.2", "1.0")
sb.AppendLine("(This is StackOverflow)'");
sb.AppendLine("ET");
然后您可以创建一个 PDF 文件并将其保存到此文件中。但是由于您想将 HTML 转换为 PDF,这可能是一项艰巨的工作,我认为您不想这样做。
或者是否有一种迂回的方法,比如在 C# UWP 应用程序中以某种方式使用 Javascript 和 https://github.com/MrRio/jsPDF?我不确定,抓着稻草……
说实话,使用Libs或Web服务将HTML转换为PDF也是一种方法,有很多,我只是搜索了它们,但是我找不到任何可以在WinRT中免费使用的。所以我认为这里最实用的方法是第一个,连接到 Microsoft Print to PDF。具体可以查看官方Printing sample。
更新:
使用@Jerry Nixon - How do I print WebView content in a Windows Store App? 中的 MSFT 代码,这是一个很好的示例。我刚刚在WebView 的NavigationCompleted 事件中添加了一些用于添加打印页面的代码:
private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
MyWebViewRectangle.Fill = await GetWebViewBrush(webView);
MyPrintPages.ItemsSource = await GetWebPages(webView, new Windows.Foundation.Size(842, 595));
}
然后在printDoc.AddPages += PrintDic_AddPages;事件中(printDoc是PrintDocument的实例):
private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
{
foreach (var item in MyPrintPages.Items)
{
var rect = item as Rectangle;
printDoc.AddPage(rect);
}
printDoc.AddPagesComplete();
}
其他代码可以参考官方打印示例。