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

我正在尝试使用 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));

                                        }



喵喵时光机
浏览 122回答 1
1回答

慕村225694

您可以直接将 pdf 文件保存在中Windows.Storage.ApplicationData.Current.LocalFolder并使用Windows.Data.Pdf 命名空间API 在应用程序中显示 pdf,而不是调用Windows.System.Launcher.LaunchFileAsync(stFile)方法来启动其他应用程序来打开 pdf 文件。有关详细信息,请参阅UWP PDF 文档示例。
打开App,查看更多内容
随时随地看视频慕课网APP