为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 xaml 页面转换为 pdf 文件并在 UWP 应用程序内的 pdf 查看器中显示?

如何将 xaml 页面转换为 pdf 文件并在 UWP 应用程序内的 pdf 查看器中显示?

C#
喵喵时光机 2022-11-21 22:06:27
我正在尝试使用 Syncfusion PDF 查看器,但为了使用它,我最终必须将 xaml 页面保存为 pdf 文件。我怎么做?我点击了此链接,但它没有给我想要的东西。XAML 到 PDF 转换我正在尝试使用下面的代码来保存 xaml 页面 [ new GenericManifestPDF(_manifestPDFDataModel); ] 从我的视图模型类中得到这个错误:' Value does not fall within the expected range ' in this line await renderTargetBitmap.RenderAsync(new GenericManifestPDF(_manifestPDFDataModel));   PdfDocument document = new PdfDocument();   //Add a new page   PdfPage page = document.Pages.Add();   //Initialize render to bitmap   var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;   var renderTargetBitmap = new RenderTargetBitmap();   //Create a Bitmap from XAML page   await renderTargetBitmap.RenderAsync(new GenericManifestPDF(_manifestPDFDataModel));   var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();   //Save the XAML in bitmap image   using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())   {   var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);   encoder.SetPixelData(   BitmapPixelFormat.Bgra8,   BitmapAlphaMode.Ignore,   (uint)renderTargetBitmap.PixelWidth,   (uint)renderTargetBitmap.PixelHeight,   logicalDpi,   logicalDpi,   pixelBuffer.ToArray());   await encoder.FlushAsync();   //Load and draw the bitmap image in PDF   PdfImage img = PdfImage.FromStream(stream.AsStream());   if (img.Width > img.Height)      document.PageSettings.Orientation = PdfPageOrientation.Portrait;          else                                                                                      document.PageSettings.Orientation = PdfPageOrientation.Landscape;       var section = document.Sections.Add();       section.PageSettings.Size = new SizeF(img.Width, img.Height);       page = section.Pages.Add();       page.Graphics.DrawImage(img, new RectangleF(0, 0, img.Width, img.Height));                                        }
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

您可以直接将 pdf 文件保存在中Windows.Storage.ApplicationData.Current.LocalFolder并使用Windows.Data.Pdf 命名空间API 在应用程序中显示 pdf,而不是调用Windows.System.Launcher.LaunchFileAsync(stFile)方法来启动其他应用程序来打开 pdf 文件。

有关详细信息,请参阅UWP PDF 文档示例。


查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 121 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号