打印BitmapImage的PDF / ObservableCollection

时间:2018-02-27 12:14:00

标签: c# pdf uwp

我一直在阅读StackOverflows关于在UWP中打印PDF的限制。其中一个主题How to print PDF in UWP without loosing quality after rasterization to PNG很好地总结了它。

我采取了以下步骤来打印PDF文件的图像

  1. 从本地文件夹

    加载PDF
    StorageFile f = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("pdffile.pdf");
    PdfDocument doc = await PdfDocument.LoadFromFileAsync(f);
    Load(doc);
    
  2. 将PDF转换为图像并将图像放入可观察的集合并将其保存到本地文件夹

    async void Load(PdfDocument pdfDoc)
    {
        PdfPages.Clear();
    
        for (uint i = 0; i < pdfDoc.PageCount; i++)
        {
            BitmapImage image = new BitmapImage();
    
            var page = pdfDoc.GetPage(i);
    
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await page.RenderToStreamAsync(stream);
                await image.SetSourceAsync(stream);
            }
    
            PdfPages.Add(image);
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("pdffilepage" + i +".jpg");
    
            var stream2 = await file.OpenStreamForWriteAsync();
            var serializer = new DataContractSerializer(typeof(ObservableCollection<BitmapImage>));
    
            serializer.WriteObject(stream2, PdfPages[(int)i]);
            await stream2.FlushAsync();
        }
        Debug.WriteLine("Writing file finished");
    }
    
  3. 在此步骤中,我收到以下错误:

      

    System.Runtime.Serialization.InvalidDataContractException:“类型'Windows.UI.Xaml.Media.ImageSource'无法序列化。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。或者,您可以确保该类型是公共的并且具有无参数构造函数 - 然后将序列化该类型的所有公共成员,并且不需要任何属性。“

    我不知道如何处理上述错误。

1 个答案:

答案 0 :(得分:1)

异常消息已清楚解释。您无法序列化ImageSource的类型。

如果要将BitmapImage保存到StorageFile中,可以使用BitmapDecoder&amp; BitmapEncoderWriteableBitmap

请参阅此主题以获取更多详细信息:Storing a BitmapImage in LocalFolder - UWP

相关问题