You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WinRT Print API打印PDF/XPS:是否必须转换为XAML?

解决方案

1. 优化PDF光栅化分辨率,解决打印模糊问题

你当前的代码没有设置渲染分辨率,默认会以屏幕DPI(通常96DPI)渲染PDF页面,而打印需要更高的DPI(比如300DPI),这是导致文本模糊的核心原因。只需调整PdfPageRenderOptions的参数,按打印DPI缩放渲染尺寸即可:

private async Task<Microsoft.UI.Xaml.UIElement> GetPdfImage(uint pageNumber)
{
    // 打印常用DPI,可根据需求调整(如300、600)
    const int printDpi = 300;
    // 屏幕默认DPI
    const int screenDpi = 96;

    PdfPageRenderOptions options = new PdfPageRenderOptions();
    using PdfPage page = pdfDoc.GetPage(Math.Max(0, pageNumber - 1));

    // 计算打印所需的高分辨率尺寸
    double scaleFactor = (double)printDpi / screenDpi;
    options.DestinationWidth = (uint)Math.Round(page.Size.Width * scaleFactor);
    options.DestinationHeight = (uint)Math.Round(page.Size.Height * scaleFactor);

    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
    await page.RenderToStreamAsync(stream, options);
    
    BitmapImage src = new BitmapImage();
    await src.SetSourceAsync(stream);

    Microsoft.UI.Xaml.Controls.Image image = new Microsoft.UI.Xaml.Controls.Image();
    image.Source = src;
    image.Stretch = Microsoft.UI.Xaml.Media.Stretch.None;
    // 保持原始页面的布局尺寸,避免打印时缩放变形
    image.Width = page.Size.Width;
    image.Height = page.Size.Height;
    return image;
}

2. 并非必须转换为XAML

WinRT Print API确实要求传入UIElement作为打印内容,但转换为XAML并不是唯一方式:

  • 优化上述光栅化逻辑后,就能输出高质量的PDF打印内容,无需重构为XAML结构;
  • 如果你的场景不需要自定义打印UI(比如页眉页脚、内容拼接),也可以直接使用PdfDocument的原生打印能力,通过系统打印对话框直接打印PDF文件流,跳过PrintDocument.AddPage的流程。

内容的提问来源于stack exchange,提问作者ekalchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:22:33