//public async Task OpenRemote(string pdfUrl) { // var client = new System.Net.Http.HttpClient(); // using(var stream = await client.GetStreamAsync(pdfUrl)) { // using(var memStream = new MemoryStream()) { // await stream.CopyToAsync(memStream); // memStream.Position = 0; // _doc = await PdfDocument.LoadFromStreamAsync(memStream.AsRandomAccessStream()); // } // } //} #endregion public async Task TakeAShot(PdfDocument doc, string name) { var fld = ApplicationData.Current.LocalFolder; if (!name.Contains(".pdf")) { name += ".pdf"; } try { await fld.GetFileAsync(name + ".jpg"); } catch (FileNotFoundException) { var r = new PdfPageRenderOptions { DestinationHeight = 190, DestinationWidth = 160 }; using (var stream = new InMemoryRandomAccessStream()) { try { await doc.GetPage(0).RenderToStreamAsync(stream, r); var fll = await fld.CreateFileAsync(name + ".jpg", CreationCollisionOption.ReplaceExisting); using (var fs = await fll.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fs.GetOutputStreamAt(0)); } } catch { Helper.GarbageCollector(); } } } }
private async Task LoadPdfFileAsync(StorageFile selectedFile) { PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(selectedFile);; if (pdfDocument != null && pdfDocument.PageCount > 0) { PageCount = pdfDocument.PageCount; for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++) { var pdfPage = pdfDocument.GetPage((uint)pageIndex); if (pdfPage != null) { MemoryStream ImageStream = new MemoryStream(); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationWidth = (uint)(1024); await pdfPage.RenderToStreamAsync(ImageStream.AsRandomAccessStream(), pdfPageRenderOptions); ImageStream.Position = 0; Image i = new Image(); i.Load(new MemoryBuffer(ImageStream)); i.Name = "Page_" + pageIndex.ToString(); ResourceCache.AddManualResource(i); pdfPage.Dispose(); } } } }
/// <summary> /// Save a rendered pdf page with inking to png file. /// </summary> /// <param name="pageNumber"></param> /// <param name="saveFile"></param> /// <returns></returns> public async Task ExportPageImage(int pageNumber, InkCanvas inkCanvas, StorageFile saveFile) { CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96 * 2); // Render pdf page InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); PdfPage page = PdfDoc.GetPage(Convert.ToUInt32(pageNumber - 1)); PdfPageRenderOptions options = new PdfPageRenderOptions(); options.DestinationWidth = (uint)inkCanvas.ActualWidth * 2; await page.RenderToStreamAsync(stream, options); CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(device, stream, 96 * 2); // Draw image with ink using (var ds = renderTarget.CreateDrawingSession()) { ds.Clear(Windows.UI.Colors.White); ds.DrawImage(bitmap); ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes()); } // Encode the image to the selected file on disk using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f); }
private async Task Save5(PdfDocument pdfDocument, ZipArchive archive, int keta, int quality, double dpi) { for (int i = 0; i < MyPdfDocument.PageCount; i++) { int renban = i + 1; string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + ".jpg"; using (PdfPage page = pdfDocument.GetPage((uint)i)) { var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = quality; encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); var entry = archive.CreateEntry(jpegName); //open using (var entryStream = entry.Open()) { using (var jpegStream = new MemoryStream()) { encoder.Save(jpegStream); jpegStream.Position = 0; jpegStream.CopyTo(entryStream); } } } } } }
/// <summary> /// The save page to jpg. /// </summary> /// <param name="numPage"> /// The num page. /// </param> /// <param name="outputFile"> /// The output file. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task SavePageToJpg(uint numPage, IStorageFile outputFile) { var page = this.pdfDocument.GetPage(numPage); var stream = new InMemoryRandomAccessStream(); var pdfPageRenderOptions = new PdfPageRenderOptions { DestinationHeight = (uint)page.Size.Height * this.Resolution }; await page.RenderToStreamAsync(stream, pdfPageRenderOptions); // initialize with 1,1 to get the current size of the image var writeableBmp = new WriteableBitmap(1, 1); writeableBmp.SetSource(stream); // and create it again because otherwise the WB isn't fully initialized and decoding // results in a IndexOutOfRange writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight); stream.Seek(0); writeableBmp.SetSource(stream); await this.SaveToFile(writeableBmp, outputFile); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { #region LoadFile try { _doc = await _pdfHelper.OpenLocal(_sfile); } catch { var dialog = new MessageDialog("Error! Wrong Password or corrupted file"); dialog.Commands.Add(new UICommand("Close")); await dialog.ShowAsync(); } #endregion if (_doc == null) { Frame.Navigate(typeof(WelcomePage)); return; } #region Load UI & Settings _ro = new PdfPageRenderOptions { DestinationWidth = (uint)(Sc.ActualWidth * 1.4), IsIgnoringHighContrast = true }; await _pdfHelper.TakeAShot(_doc, _sfile.DisplayName); _maxPage = _doc.PageCount; maxPgNr.Text = _maxPage.ToString(); current.Text = _currentPgNr.ToString(); #region Bookmark _bookMarkUser = _pdfHelper.LoadBookMarks(_sfile.Path); BkMrkBtn.IsChecked = _bookMarkUser.Contains(_currentPgNr); #endregion _isNigthMode = LocalSettingManager.ExistsSetting(App.SettingStrings["night"]); ApplicationView.GetForCurrentView().Title = _sfile.DisplayName; InkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.None; #endregion GoToPage(_currentPgNr); if (_pdfHelper.ChangeRenderBg(_ro)) { AttachRenderToImage(); } _pdfHelper.Save4WelcomePage(_sfile, _doc.PageCount); #region If Mobile if (AnalyticsInfo.VersionInfo.DeviceFamily.Contains("Desktop")) { Window.Current.CoreWindow.KeyUp += CoreWindow_KeyDown; FindName("F11Btn"); if (LocalSettingManager.ExistsSetting(App.SettingStrings["zoom"])) { FindName("ZoomTool"); (ZoomTool.Children[0] as AppBarButton).Click += ZoomOut_Click; (ZoomTool.Children[1] as AppBarButton).Click += ZoomIn_Click; } } else { PdfImg.ManipulationMode = ManipulationModes.System; PdfImg.ManipulationDelta += (x, y) => { y.Handled = false; }; } #endregion }
//public ObservableCollection<BitmapImage> PdfPages // { // get; // set; //} = new ObservableCollection<BitmapImage>(); async void LoadPdf(PdfDocument pdfDoc, int qualityRatio = 1) { //PdfPages.Clear(); //for (uint i = 0; i < pdfDoc.PageCount; i++) //{ BitmapImage image = new BitmapImage(); var page = pdfDoc.GetPage(0); using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { var opt = new PdfPageRenderOptions { DestinationWidth = (uint)page.Size.Width * (uint)qualityRatio, DestinationHeight = (uint)page.Size.Height * (uint)qualityRatio }; await page.RenderToStreamAsync(stream, opt); await image.SetSourceAsync(stream); } //PdfPages.Add(image); ImagePdfPage.Source = image; // } }
/// <summary> /// jpeg画像で保存 /// </summary> private async Task SaveSub2_1(int pageIndex, int keta, bool isJpeg) { var encoder = MakeEncoder(isJpeg); using (PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { string ext = isJpeg ? ".jpg" : ".png"; //指定されたdpiを元に画像サイズ指定、四捨五入 var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (MyDpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ //streamから直接BitmapFrameを作成することができた encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); //連番ファイル名を作成して保存 pageIndex++; string renban = pageIndex.ToString("d" + keta); using (var fileStream = new FileStream( System.IO.Path.Combine(MyPdfDirectory, MyPdfName) + "_" + renban + ext, FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } }
private async void LoadPdfFileAsync(StorageFile selectedFile) { // LogHelper.LogActivityDebug("EspaceTablette.Pages.PdfViewer.LoadPdfFileAsync | Entrée"); _pdfDocument = await PdfDocument.LoadFromFileAsync(selectedFile);; ObservableCollection <SampleDataItem> l_items = new ObservableCollection <SampleDataItem>(); this.DefaultViewModel["Items"] = l_items; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { for (int l_pageIndex = 0; l_pageIndex < _pdfDocument.PageCount; l_pageIndex++) { try { PdfPage l_pdfPage = _pdfDocument.GetPage((uint)l_pageIndex); if (l_pdfPage != null) { BitmapImage l_imgSrc = new BitmapImage(); using (IRandomAccessStream l_randomStream = new InMemoryRandomAccessStream()) { PdfPageRenderOptions l_pdfPageRenderOptions = new PdfPageRenderOptions(); l_pdfPageRenderOptions.DestinationWidth = (uint)((Window.Current.Bounds.Width - 130) / ResolutionScale() * 100); l_pdfPageRenderOptions.IsIgnoringHighContrast = true; await l_pdfPage.RenderToStreamAsync(l_randomStream, l_pdfPageRenderOptions); await l_randomStream.FlushAsync(); await l_imgSrc.SetSourceAsync(l_randomStream); } l_pdfPage.Dispose(); l_items.Add(new SampleDataItem( l_pageIndex.ToString(), l_pageIndex.ToString(), l_imgSrc)); Image l_printableImage = new Image(); l_printableImage.Stretch = Stretch.Uniform; l_printableImage.Source = l_imgSrc; m_pages.Add(l_printableImage); //inPage.CurrentPrintType = WebViewPage.PrintType.PdfDocument; } } catch (Exception ex) { //if (App.Debug) //{ // LogHelper.LogActivityWithException(l_ex, "Exception"); //} } } } }
private async void MainWindow_LoadedGood(object sender, RoutedEventArgs e) { int nPages = 0; var dpPage = new DockPanel(); this.Content = dpPage; foreach (var pdfFile in Directory.GetFiles(Rootfolder, "*.pdf", SearchOption.AllDirectories)) { var f = await StorageFile.GetFileFromPathAsync(pdfFile); var pdfDoc = await PdfDocument.LoadFromFileAsync(f); for (int i = 0; i < pdfDoc.PageCount; i++) { using (var pdfPage = pdfDoc.GetPage((uint)i)) { var bmi = new BitmapImage(); using (var strm = new InMemoryRandomAccessStream()) { var rect = pdfPage.Dimensions.ArtBox; var renderOpts = new PdfPageRenderOptions { DestinationWidth = (uint)(rect.Width + 100 * (_Rand.Next(100) - 100)), DestinationHeight = (uint)(rect.Height + 200 * (_Rand.Next(200) - 100)) }; if (pdfPage.Rotation != PdfPageRotation.Normal) { renderOpts.DestinationHeight = (uint)rect.Width; renderOpts.DestinationWidth = (uint)rect.Height; } await pdfPage.RenderToStreamAsync(strm, renderOpts); bmi.BeginInit(); bmi.StreamSource = strm.AsStream(); bmi.CacheOption = BitmapCacheOption.OnLoad; bmi.Rotation = (Rotation)(i % 4); bmi.EndInit(); //var img = new Image() //{ // Source= bmi //}; var imb = new ImageBrush(bmi); var inkc = new InkCanvas() { Background = imb, EditingMode = InkCanvasEditingMode.None }; dpPage.Children.Clear(); dpPage.Children.Add(inkc); // this.Content = inkc; } } this.Title = $"Pages = {nPages++} Curpg={i} {System.IO.Path.GetFileNameWithoutExtension(pdfFile)}"; } } }
/// <summary> /// Initialize with the page that we should track. /// </summary> /// <param name="pageInfo">A stream of cache tags and the PDF pages associated with it.</param> /// <remarks>We are really only interested in the first PdfPage we get - and we will re-subscribe, but not hold onto it.</remarks> public PDFPageViewModel(IObservable <Tuple <string, IObservable <PdfPage> > > pageInfo, IBlobCache cache = null) { _cache = cache ?? Blobs.LocalStorage; // Render an image when: // - We have at least one render request // - ImageStream is subscribed to // - the file or page updates somehow (new pageInfo iteration). // // Always pull from the cache first, but if that doesn't work, then render and place // in the cache. // Get the size of the thing when it is requested. This sequence must be finished before // any size calculations can be done! var imageSize = from pgInfo in pageInfo from sz in _cache.GetOrFetchPageSize(pgInfo.Item1, () => pgInfo.Item2.Take(1).Select(pdf => pdf.Size.ToIWalkerSize())) select new { PGInfo = pgInfo, Size = sz }; var publishedSize = imageSize .Do(info => _pageSize = info.Size) .Select(info => info.PGInfo) .Publish().RefCount(); _pageSizeLoaded = publishedSize.AsUnit(); // The render request must be "good" - that is well formed. Otherwise // we will just ignore it. This is because sometimes when things are being "sized" the // render request is malformed. RenderImage = ReactiveCommand.Create(); var renderRequest = RenderImage .Cast <Tuple <RenderingDimension, double, double> >() .Where(info => (info.Item1 == RenderingDimension.Horizontal && info.Item2 > 0) || (info.Item1 == RenderingDimension.Vertical && info.Item3 > 0) || (info.Item1 == RenderingDimension.MustFit && info.Item2 > 0 && info.Item3 > 0) ); // Generate an image when we have a render request and a everything else is setup. ImageStream = from requestInfo in Observable.CombineLatest(publishedSize, renderRequest, (pSize, rr) => new { pgInfo = pSize, RenderRequest = rr }) let imageDimensions = CalcRenderingSize(requestInfo.RenderRequest.Item1, requestInfo.RenderRequest.Item2, requestInfo.RenderRequest.Item3) from imageData in _cache.GetOrFetchPageImageData(requestInfo.pgInfo.Item1, imageDimensions.Item1, imageDimensions.Item2, () => requestInfo.pgInfo.Item2.SelectMany(pdfPg => { var ms = new MemoryStream(); var ra = WindowsRuntimeStreamExtensions.AsRandomAccessStream(ms); var opt = new PdfPageRenderOptions() { DestinationWidth = (uint)imageDimensions.Item1, DestinationHeight = (uint)imageDimensions.Item2 }; return(Observable.FromAsync(() => pdfPg.RenderToStreamAsync(ra).AsTask()) .Select(_ => ms.ToArray())); })) select new MemoryStream(imageData); }
public bool ChangeRenderBg(PdfPageRenderOptions renderOptions) { var temp = LocalSettingManager.ExistsSetting(App.SettingStrings["bgColor"]); if (temp) { renderOptions.BackgroundColor = Helper.Convert_HexColor(LocalSettingManager.ReadSetting(App.SettingStrings["bgColor"])).Color; } return(temp); }
private async void ViewPage() { rootPage.NotifyUser("", NotifyType.StatusMessage); uint pageNumber; if (!uint.TryParse(PageNumberBox.Text, out pageNumber) || (pageNumber < 1) || (pageNumber > pdfDocument.PageCount)) { rootPage.NotifyUser("Invalid page number.", NotifyType.ErrorMessage); return; } Output.Source = null; ProgressControl.Visibility = Visibility.Visible; // Convert from 1-based page number to 0-based page index. uint pageIndex = pageNumber - 1; using (PdfPage page = pdfDocument.GetPage(pageIndex)) { var stream = new InMemoryRandomAccessStream(); switch (Options.SelectedIndex) { // View actual size. case 0: await page.RenderToStreamAsync(stream); break; // View half size on beige background. case 1: var options1 = new PdfPageRenderOptions(); options1.BackgroundColor = Windows.UI.Colors.Beige; options1.DestinationHeight = (uint)(page.Size.Height / 2); options1.DestinationWidth = (uint)(page.Size.Width / 2); await page.RenderToStreamAsync(stream, options1); break; // Crop to center. case 2: var options2 = new PdfPageRenderOptions(); var rect = page.Dimensions.TrimBox; options2.SourceRect = new Rect(rect.X + rect.Width / 4, rect.Y + rect.Height / 4, rect.Width / 2, rect.Height / 2); await page.RenderToStreamAsync(stream, options2); break; } BitmapImage src = new BitmapImage(); Output.Source = src; await src.SetSourceAsync(stream); } ProgressControl.Visibility = Visibility.Collapsed; }
/// <summary> /// PdfDocumentをjpegにして、1つのzipファイルにする /// </summary> /// <param name="pdfDocument">Windows.Data.Pdf</param> /// <param name="dpi">PDFを画像にするときに使う</param> /// <param name="directory">保存フォルダ</param> /// <param name="fileName">zipファイル名とjpegファイル名に使う</param> /// <param name="quality">jpeg品質</param> /// <param name="keta">0埋め連番の桁数、jpegファイル名に使う</param> /// <returns></returns> private async Task SaveSub3_1(PdfDocument pdfDocument, double dpi, string directory, string fileName, int quality, int keta, bool isJpeg) { string exte = isJpeg ? ".jpg" : ".png"; BitmapEncoder encoder; string zipName = System.IO.Path.Combine(directory, fileName) + ".zip"; using (var zipstream = File.Create(zipName)) { using (ZipArchive archive = new ZipArchive(zipstream, ZipArchiveMode.Create)) { for (int i = 0; i < MyPdfDocument.PageCount; i++) { int renban = i + 1; string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + exte; if (isJpeg) { JpegBitmapEncoder j = new JpegBitmapEncoder(); j.QualityLevel = quality; encoder = j; } else { encoder = new PngBitmapEncoder(); } using (PdfPage page = pdfDocument.GetPage((uint)i)) { var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); var entry = archive.CreateEntry(jpegName); //open using (var entryStream = entry.Open()) { using (var jpegStream = new MemoryStream()) { encoder.Save(jpegStream); jpegStream.Position = 0; jpegStream.CopyTo(entryStream); } } } } }//for } } }
private async void LoadPdfFileAsync(StorageFile selectedFile) { try { StorageFile pdfFile = selectedFile; //Load Pdf File PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);; ObservableCollection <SampleDataItem> items = new ObservableCollection <SampleDataItem>(); this.DefaultViewModel["Items"] = items; if (pdfDocument != null && pdfDocument.PageCount > 0) { //Get Pdf page for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++) { var pdfPage = pdfDocument.GetPage((uint)pageIndex); if (pdfPage != null && navigate == false) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile pngFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (pngFile != null) { IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationWidth = (uint)(this.ActualWidth - 130); await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); await randomStream.FlushAsync(); if (navigate == false) { randomStream.Dispose(); pdfPage.Dispose(); items.Add(new SampleDataItem( pageIndex.ToString(), pageIndex.ToString(), pngFile.Path)); } } } } } } catch (Exception err) { } }
/// <summary> /// Render a pdf page to bitmap image. /// </summary> /// <param name="pageNumber">Page number</param> /// <param name="renderWidth">Desired pixel width of the image</param> /// <returns></returns> private async Task <BitmapImage> RenderPageImage(int pageNumber, uint renderWidth) { // Render pdf image InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); PdfPage page = pdfModel.GetPage(pageNumber); PdfPageRenderOptions options = new PdfPageRenderOptions(); options.DestinationWidth = renderWidth; await page.RenderToStreamAsync(stream, options); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return(bitmapImage); }
/// <summary> /// Renders a page of the loaded PDF document. /// </summary> /// <param name="pageNumber">1-based page number.</param> /// <param name="renderWidth">Page width for rendering</param> /// <returns></returns> public async Task <BitmapImage> RenderPageImage(int pageNumber, uint renderWidth) { // Render pdf image InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); PdfPage page = PdfDoc.GetPage(Convert.ToUInt32(pageNumber - 1)); PdfPageRenderOptions options = new PdfPageRenderOptions(); options.DestinationWidth = renderWidth; await page.RenderToStreamAsync(stream, options); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return(bitmapImage); }
private static async Task<string> RenderPage(Windows.Data.Pdf.PdfPage page, StorageFolder output) { var pagePath = string.Format("{0}.png", page.Index); var pageFile = await output.CreateFileAsync(pagePath, CreationCollisionOption.ReplaceExisting); using (var imageStream = await pageFile.OpenAsync(FileAccessMode.ReadWrite)) { PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.IsIgnoringHighContrast = false; await page.RenderToStreamAsync(imageStream, pdfPageRenderOptions); await imageStream.FlushAsync(); } return output.Path.ToFolderPath() + pagePath; }
//PDFファイルを画像に変換して表示 private async void DisplayImage(int pageIndex, double dpi) { if (MyPdfDocument == null) { return; } int c = (int)MyPdfDocument.PageCount - 1; if (pageIndex > c) { pageIndex = c; } if (pageIndex < 0) { pageIndex = 0; } MyDpi = dpi; using (PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { //作成する画像の縦ピクセル数を指定されたdpiから決める var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); options.DestinationWidth = (uint)Math.Round(page.Size.Width * (dpi / 96.0), MidpointRounding.AwayFromZero); tbDpi.Text = $"{dpi.ToString()} dpi"; tbHeight.Text = $"縦{options.DestinationHeight.ToString()} px"; tbWidth.Text = $"横{options.DestinationWidth.ToString()} px"; //画像に変換 using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換はstreamへ BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream();//using System.IOがないとエラーになる image.EndInit(); MyImage.Source = image; MyImage.Width = image.PixelWidth; MyImage.Height = image.PixelHeight; //プレビュー用のjpeg画像表示 MyImagePreviwer.Source = MakeJpegPreviewImage(image, GetJpegQualityFix()); UpdateDisplayPngSize(image);//pngサイズ表示更新 } } }
private static async Task <string> RenderPage(Windows.Data.Pdf.PdfPage page, StorageFolder output) { var pagePath = string.Format("{0}.png", page.Index); var pageFile = await output.CreateFileAsync(pagePath, CreationCollisionOption.ReplaceExisting); using (var imageStream = await pageFile.OpenAsync(FileAccessMode.ReadWrite)) { PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.IsIgnoringHighContrast = false; await page.RenderToStreamAsync(imageStream, pdfPageRenderOptions); await imageStream.FlushAsync(); } return(output.Path.ToFolderPath() + pagePath); }
public static async Task <IEnumerable <ImageSource> > GetImagesFromPdfUrlAsync(Uri url, int qalityRatio = 1) { var result = new List <ImageSource>(); try { var reference = RandomAccessStreamReference.CreateFromUri(url); using (var stream = await reference.OpenReadAsync()) { var document = await PdfDocument.LoadFromStreamAsync(stream); for (uint i = 0; i < document.PageCount; i++) { using (var page = document.GetPage(i)) { using (var memoryStream = new MemoryStream()) { using (var randomStream = memoryStream.AsRandomAccessStream()) { var image = new BitmapImage(); var options = new PdfPageRenderOptions { DestinationWidth = (uint)page.Size.Width * (uint)qalityRatio, DestinationHeight = (uint)page.Size.Height * (uint)qalityRatio }; await page.RenderToStreamAsync(randomStream, options); image.SetSource(randomStream); result.Add(image); } } } } } } catch (Exception ex) { Debug.WriteLine("ERROR: Unable to convert PDF to Image. " + ex.Message); } return(result); }
private async void BrowseForFileAsync() { var picker = new FileOpenPicker(); picker.FileTypeFilter.Add(".pdf"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { App.ViewModel.AllDocuments.Clear(); var pdfDocument = await PdfDocument.LoadFromFileAsync(file); var pageCount = pdfDocument.PageCount; loadingProgress.Visibility = Visibility.Visible; loadingProgress.Minimum = 1; loadingProgress.Maximum = pageCount; for (int i = 0; i < pageCount; i++) { using (PdfPage page = pdfDocument.GetPage((uint)i)) { loadingProgress.Value = i + 1; var stream = new InMemoryRandomAccessStream(); var options1 = new PdfPageRenderOptions(); await page.RenderToStreamAsync(stream); BitmapImage src = new BitmapImage(); await src.SetSourceAsync(stream); App.ViewModel.AllDocuments.Add(new Common.RenderedDocument() { PageNumber = i, PageImage = src, }); } } } loadingProgress.Visibility = Visibility.Collapsed; }
/// <summary> /// Decodes a PdfPage from the currentPdfDocument and returns it as a BitmapImage with the /// currently set PdfBackgroundColor. /// </summary> /// <param name="pageIndex"></param> /// <returns>BitmapImage</returns> private async Task <BitmapImage> GetPageImage(uint pageIndex) { BitmapImage src = null; try { if (null != _currentPdfDocument && pageIndex < _currentPdfDocument.PageCount) { using (PdfPage page = _currentPdfDocument.GetPage(pageIndex)) { var stream = new InMemoryRandomAccessStream(); var options = new PdfPageRenderOptions(); // the Beige default is set in the constructor and that will // be used to render the Pdf document unless the caller has // set that property to something else. options.BackgroundColor = PdfBackgroundColor; // View actual size. await page.RenderToStreamAsync(stream, options); src = new BitmapImage(); await src.SetSourceAsync(stream); } } else { PdfErrorMessage = string.Format("GetPageImage({0}) pageIndex out of range.", pageIndex); HostErrorMsgHandler?.Invoke(PdfErrorMessage); } } catch (Exception ex) { PdfErrorMessage = string.Format("Exception in GetPageImage({0}):{1}", pageIndex, ex.Message); } // null is the error return return(src); }
/// <summary> /// The load file. /// </summary> /// <param name="pdfFile"> /// The pdf file. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task LoadFromStorageFile(IStorageFile pdfFile) { this.PDFpages = new List <PDFPage>(); this.pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); this.TotalPages = this.pdfDocument.PageCount; for (uint pageNum = 0; pageNum < this.pdfDocument.PageCount; pageNum++) { var page = this.pdfDocument.GetPage(pageNum); var stream = new InMemoryRandomAccessStream(); var pdfPageRenderOptions = new PdfPageRenderOptions { DestinationHeight = (uint)page.Size.Height * this.Resolution }; await page.RenderToStreamAsync(stream, pdfPageRenderOptions); var source = new BitmapImage(); source.SetSource(stream); // Image pdfPage = new Image(); // pdfPage.HorizontalAlignment = HorizontalAlignment.Center; // pdfPage.VerticalAlignment = VerticalAlignment.Center; // pdfPage.Height = page.Size.Height; // pdfPage.Width = page.Size.Width; // pdfPage.Margin = new Thickness(0, 0, 0, 5); // pdfPage.Source = source; this.PDFpages.Add(new PDFPage { ImagePreview = source, PdfPage = page }); } }
private async System.Threading.Tasks.Task LoadPdfFileAsync(StorageFile selectedFile) { try { StorageFile pdfFile = selectedFile; //Load Pdf File PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); ; ObservableCollection<SampleDataItem> items = new ObservableCollection<SampleDataItem>(); this.DefaultViewModel["Items"] = items; if (pdfDocument != null && pdfDocument.PageCount > 0) { string uniqueName = "DncPdfReader_Temp_PDF_x4201"; m_storageFolder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync(uniqueName, CreationCollisionOption.ReplaceExisting); //Get Pdf page for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++) { //System.Diagnostics.Debug.WriteLine("Rendering pdf page"); if (m_stopRendering == true) break; var pdfPage = pdfDocument.GetPage((uint)pageIndex); if (pdfPage != null) { // next, generate a bitmap of the page StorageFile pngFile = await m_storageFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (pngFile != null) { IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationWidth = (uint)(this.ActualWidth - 130); await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); items.Add(new SampleDataItem( pageIndex.ToString(), pageIndex.ToString(), pngFile.Path)); } } } } } catch (Exception err) { } }
/// <summary> /// This renders PDF page with render options /// Rendering a pdf page requires following 3 steps /// 1. PdfDocument.LoadFromFileAsync(pdfFile) which returns pdfDocument /// 2. pdfDocument.GetPage(pageIndex) /// 3. pdfPage.RenderToStreamAsync(stream) or pdfPage.RenderToStreamAsync(stream,pdfPageRenderOptions) /// </summary> private async Task RenderPDFPage(string pdfFileName,RENDEROPTIONS renderOptions) { try { StorageFile pdfFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(pdfFileName); //Load Pdf File _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); ; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { //Get Pdf page var pdfPage = _pdfDocument.GetPage(PDF_PAGE_INDEX); if (pdfPage != null) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile jpgFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); switch (renderOptions) { case RENDEROPTIONS.NORMAL: //Render Pdf page with default options await pdfPage.RenderToStreamAsync(randomStream); break; case RENDEROPTIONS.ZOOM: //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR; //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; case RENDEROPTIONS.PORTION: //Set PDFPageRenderOptions.SourceRect to render portion of a page pdfPageRenderOptions.SourceRect = PDF_PORTION_RECT; //Render portion of a page await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; } await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); await DisplayImageFileAsync(jpgFile); } } } } catch (Exception err) { rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage); } }
public async Task<BitmapImage> RenderPageImage(int pageNumber, uint renderWidth) { // Render pdf image InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); PdfPage page = PdfDoc.GetPage(Convert.ToUInt32(pageNumber - 1)); PdfPageRenderOptions options = new PdfPageRenderOptions(); options.DestinationWidth = renderWidth; await page.RenderToStreamAsync(stream, options); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return bitmapImage; }
/// <summary> /// This renders PDF page with render options /// Rendering a pdf page requires following 3 steps /// 1. PdfDocument.LoadFromFileAsync(pdfFile) which returns pdfDocument /// 2. pdfDocument.GetPage(pageIndex) /// 3. pdfPage.RenderToStreamAsync(stream) or pdfPage.RenderToStreamAsync(stream,pdfPageRenderOptions) /// </summary> private async Task RenderPDFPage(string pdfFileName, RENDEROPTIONS renderOptions) { try { StorageFile pdfFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(pdfFileName); //Load Pdf File _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { //Get Pdf page var pdfPage = _pdfDocument.GetPage(PDF_PAGE_INDEX); if (pdfPage != null) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile jpgFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); switch (renderOptions) { case RENDEROPTIONS.NORMAL: //Render Pdf page with default options await pdfPage.RenderToStreamAsync(randomStream); break; case RENDEROPTIONS.ZOOM: //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR; //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; case RENDEROPTIONS.PORTION: //Set PDFPageRenderOptions.SourceRect to render portion of a page pdfPageRenderOptions.SourceRect = PDF_PORTION_RECT; //Render portion of a page await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; } await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); await DisplayImageFileAsync(jpgFile); } } } } catch (Exception err) { rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage); } }
private async void LoadDatasheet() { PdfDocument pdfDocument; try { _pdfFile = await DownloadDatasheet(); if (_pdfFile != null) { IsDownloadingDatasheet = false; IsLoadingDatasheet = true; pdfDocument = await PdfDocument.LoadFromFileAsync(_pdfFile); _datasheetPages = new BindableCollection <DatasheetPage>(); if (pdfDocument != null) { for (uint i = 0; i < pdfDocument.PageCount; i++) { var pdfPage = await Task.Run(() => pdfDocument.GetPage(i)); if (pdfPage != null) { // TODO : add images in a specific folder in temp StorageFile pngFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (pngFile != null) { IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationHeight = (uint)pdfPage.Dimensions.ArtBox.Height * 2; pdfPageRenderOptions.DestinationWidth = (uint)pdfPage.Dimensions.ArtBox.Width * 2; await pdfPage.RenderToStreamAsync(randomStream); await randomStream.FlushAsync(); randomStream.Dispose(); DatasheetPage page = new DatasheetPage(pdfPage.Index + 1, pdfPage.Dimensions.ArtBox, pngFile.Path); pdfPage.Dispose(); _datasheetPages.Add(page); NotifyOfPropertyChange <BindableCollection <DatasheetPage> >(() => DatasheetPages); } } } } IsLoadingDatasheet = false; } else { // TODO : afficher un message d'erreur await SeeDatasheetOnBrowser(); GoBack(); } } catch (Exception) { IsLoadingDatasheet = false; IsDownloadingDatasheet = false; //TODO : gerer l'erreur } }
private async void RenderPage(PdfPage pdfPage) { Stopwatch sw = new Stopwatch(); sw.Start(); canvas.Children.Clear(); await pdfPage.PreparePageAsync(); StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile jpgFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.GenerateUniqueName); PdfPageRenderOptions renderOptions = new PdfPageRenderOptions(); renderOptions.DestinationHeight = (uint)(pdfPage.Size.Height * 2.0); renderOptions.DestinationWidth = (uint)(pdfPage.Size.Width * 2.0); canvas.Width = renderOptions.DestinationWidth; canvas.Height = renderOptions.DestinationHeight; if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); await pdfPage.RenderToStreamAsync(randomStream, renderOptions); await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); //await DisplayImageFileAsync(jpgFile); } SoftwareBitmap softwareBitmap; BitmapImage image = new BitmapImage(); ImageBrush backgroundBrush = new ImageBrush(); using (IRandomAccessStream stream = await jpgFile.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); image.SetSource(stream); backgroundBrush.ImageSource = image; // Get the SoftwareBitmap representation of the file softwareBitmap = await decoder.GetSoftwareBitmapAsync(); } OcrEngine engine = OcrEngine.TryCreateFromUserProfileLanguages(); var result = await engine.RecognizeAsync(softwareBitmap); textBox.Text = ""; var left = canvas.GetValue(Canvas.LeftProperty); var top = canvas.GetValue(Canvas.TopProperty); foreach (OcrLine line in result.Lines) { Rectangle lineRect = new Rectangle(); textBox.Text += line.Text + "\r\n"; foreach (OcrWord word in line.Words) { Rectangle r = new Rectangle(); r.Margin = new Thickness(word.BoundingRect.Left, word.BoundingRect.Top, 0.0, 0.0); r.Width = word.BoundingRect.Width; r.Height = word.BoundingRect.Height; r.Stroke = new SolidColorBrush(Colors.Blue); canvas.Children.Add(r); canvas.Background = backgroundBrush; } } // Looking for line "Duration of agreement" for (int i = 0; i < result.Lines.Count; i++) { OcrLine line = result.Lines[i]; if (line.Text.Contains("Customer Name")) { clientName.Text = line.Text.Substring(13); //MessageDialog dlg = new MessageDialog(clientName.Text); //await dlg.ShowAsync(); } } sw.Stop(); MessageDialog md = new MessageDialog(string.Format("Page processed in {0} milliseconds", sw.ElapsedMilliseconds)); await md.ShowAsync(); }
/// <summary> /// Maakt voor elk aangemaakt pdf bestand een nieuwe map met hierin alle pagina's apart per afbeelding. /// </summary> /// <param name="renderOption"></param> /// <param name="bestanden">Een lijst met StorageFolders instanties</param> /// <returns>Eventueel de lijst van StorageFiles indien nodig</returns> public async Task <List <StorageFile> > GetAfbeeldingenVanPDF(RENDEROPTIONS renderOption, List <StorageFile> bestanden) { List <StorageFile> paginas = new List <StorageFile>(); //Bekomen lijst van PDF pagina als afbeelding foreach (StorageFile bestand in bestanden) { string bestandsNaam = bestand.Name.Replace(".pdf", ""); //PDF extensie uit de naam wissen voor de folder try { await doelfolder.CreateFolderAsync(bestandsNaam, CreationCollisionOption.ReplaceExisting); //Maak de doelfolder aan en vervang indien nodig //PDF bestand laden PdfDocument _pdfDocument = await PdfDocument.LoadFromFileAsync(bestand);; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; for (uint pagina = 0; pagina < _pdfDocument.PageCount; pagina++) { var pdfPage = _pdfDocument.GetPage(pagina); if (pdfPage != null) { StorageFile jpgFile = await doelfolder. CreateFileAsync(String.Format("\\{0}\\{1}_pagina{2}.png", bestandsNaam, bestandsNaam, pagina), CreationCollisionOption.ReplaceExisting); if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); switch (renderOption) { case RENDEROPTIONS.NORMAL: //PDF pagina inladen await pdfPage.RenderToStreamAsync(randomStream); break; case RENDEROPTIONS.ZOOM: //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR; //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; } await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); paginas.Add(jpgFile); } } } } } catch (Exception e) { paLogging.log.Error(String.Format("Er is een fout opgetreden bij het converteren van pdf {0} naar afbeeldingen: {1}", bestandsNaam, e.Message)); } } return(paginas); //Pagina's teruggeven (leeg indien exception, e.d.) }
private PdfPageRenderOptions GetPdfRenderOptions(PdfPage pdfPage, double height, double width) { PdfPageRenderOptions output = null; if (pdfPage == null) return null; double xZoomFactor = pdfPage.Size.Height / height; // _height; double yZoomFactor = pdfPage.Size.Width / width; // _width; double zoomFactor = Math.Max(xZoomFactor, yZoomFactor); if (zoomFactor > 0) { output = new PdfPageRenderOptions() { DestinationHeight = (uint)(pdfPage.Size.Height / zoomFactor), DestinationWidth = (uint)(pdfPage.Size.Width / zoomFactor) }; } return output; }
private async void LoadPdfImage(int i, Grid imageContainer, Image img) { try { if (imageContainer.Children.Count < 3) { ProgressRing progressRing = CreateProgressRing(); imageContainer.Children.Add(progressRing); PdfPage pdfPage = _pdfDocument.GetPage((uint)i); var stream = new InMemoryRandomAccessStream(); PdfPageRenderOptions options = new PdfPageRenderOptions(); options.BitmapEncoderId = BitmapEncoder.JpegXREncoderId; options.DestinationHeight = (uint)(pdfPage.Dimensions.ArtBox.Height); options.DestinationWidth = (uint)(pdfPage.Dimensions.ArtBox.Width); await pdfPage.RenderToStreamAsync(stream, options); BitmapImage pdfImg = new BitmapImage(); pdfImg.SetSource(stream); img.Source = pdfImg; imageContainer.Height = pdfImg.PixelHeight; imageContainer.Width = pdfImg.PixelWidth; progressRing.Visibility = Visibility.Collapsed; } } catch (Exception e) { Debug.WriteLine("LoadPdfImage: "+e.ToString()); } }
/// <summary> /// Internal render method /// </summary> /// <param name="pageNumber"></param> /// <param name="rotationAngle"></param> /// <returns></returns> private async Task BackgroundPageRenderAsync() { using (PdfPage page = RenderedDocument.GetPage(renderedPageIndex)) { var renderOptions = new PdfPageRenderOptions(); renderOptions.BackgroundColor = Windows.UI.Colors.Transparent; double actualWidth = PreviewArea.ActualWidth - PreviewBorder.Margin.Left - PreviewBorder.Margin.Right - 4; ScaledRectangle displayedPageDimension; if (RenderedRotationAngle % 180 == 0) { // Raw page orientation matches displayed page orientation displayedPageDimension = new ScaledRectangle(page.Size.Height, page.Size.Width); } else { // Raw page orientation does not match the displayed page orientation displayedPageDimension = new ScaledRectangle(page.Size.Width, page.Size.Height); } double stretchedHeight = displayedPageDimension.GetScaledHeight(actualWidth); if (stretchedHeight > MaxHeight) { renderOptions.DestinationHeight = (uint)(MaxHeight); renderOptions.DestinationWidth = (uint)displayedPageDimension.GetScaledWidth(MaxHeight); } else { renderOptions.DestinationHeight = (uint)stretchedHeight; renderOptions.DestinationWidth = (uint)actualWidth; } // update decent border around the previewed page PreviewBorder.Height = renderOptions.DestinationHeight; PreviewBorder.Width = renderOptions.DestinationWidth; var stream = new InMemoryRandomAccessStream(); await page.RenderToStreamAsync(stream, renderOptions); BitmapImage src = new BitmapImage(); await src.SetSourceAsync(stream); Preview.Source = src; RotateTransform rotationTransform = new RotateTransform() { Angle = RenderedRotationAngle, CenterX = (PreviewBorder.Width - 4) / 2, CenterY = (PreviewBorder.Height - 4) / 2 }; ScaleTransform scaleTransform; if (RenderedRotationAngle % 180 == 0) { scaleTransform = new ScaleTransform() { ScaleX = 1, ScaleY = 1, }; } else { scaleTransform = new ScaleTransform() { CenterX = (PreviewBorder.Width - 4) / 2, CenterY = (PreviewBorder.Height - 4) / 2, ScaleX = displayedPageDimension.AspectRatio, ScaleY = 1 / displayedPageDimension.AspectRatio, }; } TransformGroup renderTransform = new TransformGroup(); renderTransform.Children.Add(rotationTransform); renderTransform.Children.Add(scaleTransform); Preview.RenderTransform = renderTransform; SetBorderStyle(); } }
/// <summary> /// Maakt voor elk aangemaakt pdf bestand een nieuwe map met hierin alle pagina's apart per afbeelding. /// </summary> /// <param name="renderOption"></param> /// <param name="bestanden">Een lijst met StorageFolders instanties</param> /// <returns>Eventueel de lijst van StorageFiles indien nodig</returns> public async Task<List<StorageFile>> GetAfbeeldingenVanPDF(RENDEROPTIONS renderOption, List<StorageFile> bestanden) { List<StorageFile> paginas = new List<StorageFile>(); //Bekomen lijst van PDF pagina als afbeelding foreach (StorageFile bestand in bestanden) { string bestandsNaam = bestand.Name.Replace(".pdf", ""); //PDF extensie uit de naam wissen voor de folder try { await doelfolder.CreateFolderAsync(bestandsNaam, CreationCollisionOption.ReplaceExisting); //Maak de doelfolder aan en vervang indien nodig //PDF bestand laden PdfDocument _pdfDocument = await PdfDocument.LoadFromFileAsync(bestand); ; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; for (uint pagina = 0; pagina < _pdfDocument.PageCount; pagina++) { var pdfPage = _pdfDocument.GetPage(pagina); if (pdfPage != null) { StorageFile jpgFile = await doelfolder. CreateFileAsync(String.Format("\\{0}\\{1}_pagina{2}.png", bestandsNaam, bestandsNaam, pagina), CreationCollisionOption.ReplaceExisting); if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); switch (renderOption) { case RENDEROPTIONS.NORMAL: //PDF pagina inladen await pdfPage.RenderToStreamAsync(randomStream); break; case RENDEROPTIONS.ZOOM: //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR; //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; } await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); paginas.Add(jpgFile); } } } } } catch (Exception e) { paLogging.log.Error(String.Format("Er is een fout opgetreden bij het converteren van pdf {0} naar afbeeldingen: {1}", bestandsNaam, e.Message)); } } return paginas; //Pagina's teruggeven (leeg indien exception, e.d.) }
private async System.Threading.Tasks.Task LoadPdfFileAsync() { try { StorageFile pdfFile = await ApplicationData.Current.LocalFolder.GetFileAsync("2.pdf"); //Load Pdf File pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);; ObservableCollection <SampleDataItem> items = new ObservableCollection <SampleDataItem>(); this.DefaultViewModel["Items"] = items; //StorageFolder tempFolderDel = ApplicationData.Current.TemporaryFolder; // await tempFolderDel.DeleteAsync(StorageDeleteOption.Default); // Get the app's local folder. //StorageFile localFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync("ba4755e5-520b-42eb-bcf8-1f0cddd5e5ca.png"); //await localFile.DeleteAsync(); // Create a new subfolder in the current folder. // Raise an exception if the folder already exists. //string desiredName = "TempState2"; //StorageFolder newFolder = await localFolder.CreateFolderAsync(desiredName,CreationCollisionOption.FailIfExists); if (pdfDocument != null && pdfDocument.PageCount > 0) { string file = ""; //Get Pdf page for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++) { var pdfPage = pdfDocument.GetPage((uint)pageIndex); if (pdfPage != null) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile pngFile = await tempFolder.CreateFileAsync((file = Guid.NewGuid().ToString() + ".png"), CreationCollisionOption.ReplaceExisting); files_for_Delete.Add(file); if (pngFile != null) { IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationWidth = (uint)(this.ActualWidth - 130); await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); items.Add(new SampleDataItem( pageIndex.ToString(), pageIndex.ToString(), pngFile.Path)); } } } } t = true; } catch (Exception err) { t = false; } }
/// <summary> /// This renders PDF bitmap Image with render options /// Rendering a pdf page requires following 3 steps /// 1. PdfDocument.LoadFromFileAsync(pdfFile) which returns pdfDocument /// 2. pdfDocument.GetPage(pageIndex) /// 3. pdfPage.RenderToStreamAsync(stream) or pdfPage.RenderToStreamAsync(stream,pdfPageRenderOptions) /// </summary> public static async Task<Images> LoadPDFBitmapImage(StorageFile pdfFile, RENDEROPTIONS renderOptions) { Images image = new Images(); List<ImageSource> bitmapImageListForAllPages = new List<ImageSource>(); List<WriteableBitmap> lstwriteable = new List<WriteableBitmap>(); try { //Load Pdf File PdfDocument _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); ; if (_pdfDocument != null && _pdfDocument.PageCount > 0) { for (uint i = 0; i < _pdfDocument.PageCount; i++) { //Get Pdf page var pdfPage = _pdfDocument.GetPage(i); if (pdfPage != null) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile jpgFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting); if (jpgFile != null) { IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); switch (renderOptions) { case RENDEROPTIONS.NORMAL: //Render Pdf page with default options await pdfPage.RenderToStreamAsync(randomStream); break; case RENDEROPTIONS.ZOOM: //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR; //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; case RENDEROPTIONS.PORTION: //Set PDFPageRenderOptions.SourceRect to render portion of a page pdfPageRenderOptions.SourceRect = PDF_PORTION_RECT; //Render portion of a page await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); break; } Size size = pdfPage.Size; WriteableBitmap writebitmap = new WriteableBitmap((int)size.Width, (int)size.Height); writebitmap.SetSource(randomStream); lstwriteable.Add(writebitmap); //return src; await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); // Display the image in the UI. BitmapImage src = new BitmapImage(); //src.SetSource(randomStream); src.SetSource(await jpgFile.OpenAsync(FileAccessMode.Read)); //jpgFile = await jpgFile.GetScaledImageAsThumbnailAsync(ThumbnailMode.DocumentsView, ZOOM_FACTOR, ThumbnailOptions.ResizeThumbnail); bitmapImageListForAllPages.Add(src); } } } } } catch (Exception err) { } image.ListImageDisplay.Add(bitmapImageListForAllPages); image.ListWriteImages.Add(lstwriteable); return image; }
private async void Page_Loaded(object sender, RoutedEventArgs e) { try { _doc = await _pdfHelper.OpenLocal(_sfile); } catch { var dialog = new MessageDialog("Error! Wrong Password or corrupted file"); dialog.Commands.Add(new UICommand("Close")); await dialog.ShowAsync(); } if (_doc == null) { Frame.Navigate(typeof(WelcomePage)); return; } _renderOptions = new PdfPageRenderOptions(); _isNigthMode = LocalSettingManager.ExistsSetting(App.SettingStrings["night"]); _pdfHelper.ChangeRenderBg(_renderOptions); MaxPageText.Text = _doc.PageCount.ToString(); if (LocalSettingManager.ExistsSetting(App.SettingStrings["lastPage"] + _sfile.Path)) { var saveLast = LocalSettingManager.ReadSetting(App.SettingStrings["lastPage"] + _sfile.Path); if (saveLast != "1") { FindName("GoLastPageBtn"); GoLastPageBtn.Tag = saveLast; GoLastPageBtn.Visibility = Visibility.Visible; var an = Resources["LastFadeOut"] as Storyboard; an.Completed += (o, o1) => { GoLastPageBtn.Visibility = Visibility.Collapsed; GoLastPageBtn.Click -= GoLastPageBtn_OnClick; GoLastPageBtn = null; }; an.Begin(); } } try { await Load(); } catch { Frame.Navigate(typeof(WelcomePage)); return; } _bookMarkUser = _pdfHelper.LoadBookMarks(_sfile.Path); _pdfHelper.Save4WelcomePage(_sfile, _doc.PageCount); await _pdfHelper.TakeAShot(_doc, _sfile.DisplayName); InkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.None; BkMrkBtn.IsChecked = _bookMarkUser.Contains(1); if (LocalSettingManager.ExistsSetting(App.SettingStrings["zoom"])) { FindName("ZoomTool"); (ZoomTool.Children[0] as AppBarButton).Click += ZoomOut_Click; (ZoomTool.Children[1] as AppBarButton).Click += ZoomIn_Click; } if (AnalyticsInfo.VersionInfo.DeviceFamily.Contains("Desktop")) // "Desktop" { Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown; FindName("F11Btn"); } }
private async System.Threading.Tasks.Task LoadPdfFileAsync() { try { StorageFile pdfFile = await ApplicationData.Current.LocalFolder.GetFileAsync("2.pdf"); //Load Pdf File pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); ; ObservableCollection<SampleDataItem> items = new ObservableCollection<SampleDataItem>(); this.DefaultViewModel["Items"] = items; //StorageFolder tempFolderDel = ApplicationData.Current.TemporaryFolder; // await tempFolderDel.DeleteAsync(StorageDeleteOption.Default); // Get the app's local folder. //StorageFile localFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync("ba4755e5-520b-42eb-bcf8-1f0cddd5e5ca.png"); //await localFile.DeleteAsync(); // Create a new subfolder in the current folder. // Raise an exception if the folder already exists. //string desiredName = "TempState2"; //StorageFolder newFolder = await localFolder.CreateFolderAsync(desiredName,CreationCollisionOption.FailIfExists); if (pdfDocument != null && pdfDocument.PageCount > 0) { string file = ""; //Get Pdf page for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++) { var pdfPage = pdfDocument.GetPage((uint)pageIndex); if (pdfPage != null) { // next, generate a bitmap of the page StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; StorageFile pngFile = await tempFolder.CreateFileAsync((file=Guid.NewGuid().ToString() + ".png"), CreationCollisionOption.ReplaceExisting); files_for_Delete.Add(file); if (pngFile != null) { IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite); PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions(); pdfPageRenderOptions.DestinationWidth = (uint)(this.ActualWidth - 130); await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); await randomStream.FlushAsync(); randomStream.Dispose(); pdfPage.Dispose(); items.Add(new SampleDataItem( pageIndex.ToString(), pageIndex.ToString(), pngFile.Path)); } } } } t = true; } catch (Exception err) { t = false; } }