/// <summary> /// jpeg画像で保存 /// </summary> /// <param name="dpi">PDFファイルを読み込む時のDPI</param> /// <param name="directory">保存フォルダ</param> /// <param name="fileName">保存名</param> /// <param name="pageIndex">保存するPDFのページ</param> /// <param name="quality">jpegの品質min0、max100</param> /// <param name="keta">保存名につける連番0埋めの桁数</param> /// <returns></returns> private async Task SaveSub2(double dpi, string directory, string fileName, int pageIndex, int quality, int keta) { using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { //指定されたdpiを元に画像サイズ指定、四捨五入 var options = new Windows.Data.Pdf.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); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = quality; encoder.Frames.Add(BitmapFrame.Create(image)); pageIndex++; string renban = pageIndex.ToString("d" + keta); using (var fileStream = new FileStream( System.IO.Path.Combine(directory, fileName) + "_" + renban + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } }
private async void DisplayImage(int pageIndex, double dpi) { if (MyPdfDocument == null) { return; } MyDpi = dpi; using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); tbDpi.Text = $"dpi : {dpi.ToString()}"; tbHeight.Text = $"縦ピクセル : {options.DestinationHeight.ToString()}"; using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); 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; } } }
private async void ButtonOpenScale_Click(object sender, RoutedEventArgs e) { var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf"); try { PdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file); } catch (Exception) { } if (PdfDocument != null) { using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(0)) { BitmapImage image = new BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = 1000; await page.RenderToStreamAsync(stream, options); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); } ImagePDF.Source = image; } } }
private async Task <int> SaveSubTask(double rate, string filePath, uint i) { using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage((uint)i)) { //指定されたdpiを元にレンダーサイズ指定、四捨五入 double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 85; encoder.Frames.Add(BitmapFrame.Create(image)); using (var fileStream = new FileStream(filePath + "_" + i + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } return((int)i); }
//ロックじゃない開き方 private async void ButtonFree_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf"); //ここから using (Windows.Storage.Streams.IRandomAccessStream RAStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { Windows.Data.Pdf.PdfDocument MyPdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromStreamAsync(RAStream); //ここまで using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage(0)) { using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream); var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); MyImage.Source = image; } } } }
/// <summary> /// 表示 /// </summary> /// <param name="pageNumber">指定ページ</param> /// <param name="displayDpi">指定dpi、通常なら96</param> private async void PageLoad(uint pageNumber, double displayDpi) { if (PdfDocument == null) { return; } BitmapImage image = new BitmapImage(); var rate = displayDpi / 96.0;//表示倍率みたいなもの using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(pageNumber)) { //指定されたdpiを元にレンダーサイズ指定、四捨五入 double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); } } MyImage.Source = image; MyImage.Width = image.PixelWidth; MyImage.Height = image.PixelHeight; }
private async Task <Windows.Storage.Streams.InMemoryRandomAccessStream> RenderPageBitmapAsync() { using (Windows.Data.Pdf.PdfPage pdfPage = _pdfDoc.GetPage(_currentPageIndex)) { var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await pdfPage.RenderToStreamAsync(memStream); return(memStream); } }
private void DisplayStatus() { if (PdfDocument == null) { return; } tbPagesCount.Text = PdfDocument.PageCount.ToString(); Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(0); tbDpi.Text = page.Size.Height.ToString(); page.Dispose(); }
private async Task <BitmapImage> MakeImage(Windows.Data.Pdf.PdfPage page) { var img = new BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream); img.BeginInit(); img.CacheOption = BitmapCacheOption.OnLoad; img.StreamSource = stream.AsStream(); img.EndInit(); } return(img); }
public PageMapping(Windows.Data.Pdf.PdfPage msPage, PdfLoadedPage sfPage) { Rotation = (int)msPage.Rotation; // The page size returned from Syncfusion pdf is the media box size. ScaleRatio = sfPage.Size.Width / msPage.Dimensions.MediaBox.Width; // The ink canvas size is the same as crop box // Crop box could be smaller than media box // There will be an offset if the crop box is smaller than the media box. Offset = new Point( msPage.Dimensions.CropBox.Left * ScaleRatio, msPage.Dimensions.CropBox.Top * ScaleRatio ); PageSize = new System.Drawing.SizeF(sfPage.Size.Width, sfPage.Size.Height); Rectangle = new System.Drawing.RectangleF(0, 0, sfPage.Size.Width, sfPage.Size.Height); }
//未検証、ページから画像作成から保存までの処理をTaskにする、あとでTaskWhenAllで実行? private async Task SaveTaskAsync(Windows.Data.Pdf.PdfPage page, string directory, string fileName, int pageIndex, int quality, int keta) { using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream); var encoder = new JpegBitmapEncoder(); encoder.QualityLevel = quality; encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); string renban = pageIndex.ToString("d" + keta); using (var fileStream = new FileStream( System.IO.Path.Combine(directory, fileName) + "_" + renban + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } }
/// <summary> /// Loads the ink annotations in the PDF file. /// </summary> /// <param name="pageNumber">1-based page number.</param> /// <returns></returns> public List <InkStroke> LoadInFileInkAnnotations(int pageNumber) { List <PdfLoadedInkAnnotation> inkAnnotations = sfPdf.GetInkAnnotations(pageNumber); List <InkStroke> strokes = new List <InkStroke>(); // Get page information from SF model PdfLoadedPage sfPage = sfPdf.GetPage(pageNumber); // Get page information from MS model Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(pageNumber); // Calculate page mapping PageMapping mapping = new PageMapping(msPage, sfPage); foreach (PdfLoadedInkAnnotation annotation in inkAnnotations) { strokes.Add(mapping.InkAnnotation2InkStroke(annotation)); } return(strokes); }
private async void MakeImageAndSave(double displayDpi) { if (PdfDocument == null) { return; } string filePath = @"D:\ブログ用\1708_04"; var rate = displayDpi / 96.0;//表示倍率みたいなもの for (uint i = 0; i < PdfDocument.PageCount; i++) { using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(i)) { //指定されたdpiを元にレンダーサイズ指定、四捨五入 double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 85; encoder.Frames.Add(BitmapFrame.Create(image)); using (var fileStream = new FileStream(filePath + "_" + i + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } } }
/// <summary> /// Cache printable output /// </summary> /// <param name="p">Number of first page to print</param> /// <param name="count">Number of pages to print</param> /// <returns>Task that the caller is expected to await</returns> private async Task PrepareForPrintAsync(int p, int count /*, StorageFolder tempfolder*/) { if ((_pageImages is null) || (_pageImages.Count == 0)) { ClearCachedPages(); _pageImages = new List <Windows.UI.Xaml.Controls.Image>(); _ = new Windows.UI.Xaml.Controls.Image(); for (int i = p; i < count; i++) { ApplicationLanguages.PrimaryLanguageOverride = CultureInfo.InvariantCulture.TwoLetterISOLanguageName; Windows.Data.Pdf.PdfPage pdfPage = _pdfDocument.GetPage(uint.Parse(i.ToString())); double pdfPagePreferredZoom = pdfPage.PreferredZoom; IRandomAccessStream randomStream = new InMemoryRandomAccessStream(); global::Windows.Data.Pdf.PdfPageRenderOptions pdfPageRenderOptions = new global::Windows.Data.Pdf.PdfPageRenderOptions(); Windows.Foundation.Size pdfPageSize = pdfPage.Size; pdfPageRenderOptions.DestinationHeight = (uint)(pdfPageSize.Height * pdfPagePreferredZoom); pdfPageRenderOptions.DestinationWidth = (uint)(pdfPageSize.Width * pdfPagePreferredZoom); await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions); Windows.UI.Xaml.Controls.Image imageCtrl = new Windows.UI.Xaml.Controls.Image(); BitmapImage src = new BitmapImage(); randomStream.Seek(0); src.SetSource(randomStream); imageCtrl.Source = src; Windows.Graphics.Display.DisplayInformation DisplayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); float dpi = DisplayInformation.LogicalDpi / 96; imageCtrl.Height = src.PixelHeight / dpi; imageCtrl.Width = src.PixelWidth / dpi; randomStream.Dispose(); pdfPage.Dispose(); _pageImages.Add(imageCtrl); AddPageToCache(imageCtrl); } } }
private BitmapImage RenderPage(double dpi, int pageIndex) { BitmapImage image = new BitmapImage(); using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { //指定されたdpiを元に画像サイズ指定、四捨五入 var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { page.RenderToStreamAsync(stream, options); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); } } return(image); }
/// <summary> /// Save the ink annotations into the pdf file. /// </summary> /// <param name="inkDictionary"></param> /// <returns></returns> /// <remarks> /// The page size returned from Syncfusion pdf is the media box size. /// The page size displayed to the end user is the crop box size. /// The size of the ink canvas is the same as the crop box size. /// Syncfusion uses the bottom left corner as the origin, while ink canvas uses the top left corner. /// </remarks> public async Task <bool> SaveInkingToPdf(InkingManager inkManager) { // Indicate whether any ink annotation is added to the PDF file bool fileChanged = false; // Remove ereased ink annotations foreach (KeyValuePair <int, List <InkStroke> > entry in await inkManager.ErasedStrokesDictionary()) { // The key of the dictionary is page number, which is 1-based. int pageNumber = entry.Key; PdfLoadedPage sfPage = sfPdf.GetPage(pageNumber); // Get page information from MS model Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(pageNumber); PageMapping mapping = new PageMapping(msPage, sfPage); List <PdfInkAnnotation> erasedAnnotations = new List <PdfInkAnnotation>(); // Add each ink stroke to the page foreach (InkStroke stroke in entry.Value) { PdfInkAnnotation inkAnnotation = mapping.InkStroke2InkAnnotation(stroke); erasedAnnotations.Add(inkAnnotation); } if (sfPdf.RemoveInkAnnotations(sfPage, erasedAnnotations)) { fileChanged = true; } } // Add new ink annotations foreach (KeyValuePair <int, InkStrokeContainer> entry in await inkManager.InAppInkDictionary()) { PdfLoadedPage sfPage = sfPdf.GetPage(entry.Key); // Get page information from MS model Windows.Data.Pdf.PdfPage msPage = msPdf.GetPage(entry.Key); PageMapping mapping = new PageMapping(msPage, sfPage); // Add each ink stroke to the page foreach (InkStroke stroke in entry.Value.GetStrokes()) { PdfInkAnnotation inkAnnotation = mapping.InkStroke2InkAnnotation(stroke); sfPage.Annotations.Add(inkAnnotation); fileChanged = true; } } // Save the file only if there are changes. bool inkSaved = false; if (fileChanged) { try { inkSaved = await sfPdf.SaveAsync(); // Copy and replace the actual file await sfFile.CopyAndReplaceAsync(pdfFile); } catch (Exception ex) { // Try to save the file by extracting the pages. StorageFile newFile = await backupFolder.CreateFileAsync("COPY_" + pdfFile.Name, CreationCollisionOption.GenerateUniqueName); try { await sfPdf.CopyPages(newFile); inkSaved = true; // Copy and replace the actual file await newFile.CopyAndReplaceAsync(pdfFile); } catch { App.NotifyUser(typeof(ViewerPage), "Error: \n" + ex.Message, true); } } } return(!(inkSaved ^ fileChanged)); }
private async void btnCombinar_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { if (model.Etiquetas.Count() > 0) { try { model.ScenarioRunning = true; Models.Etiquetas.Etiquetas_GetArchivosBindingModel mdl = new Models.Etiquetas.Etiquetas_GetArchivosBindingModel(); mdl.Aplicacion = model.Aplicacion; mdl.Categoria = model.Categoria; mdl.Etiquetas = model.Etiquetas; long IDArchivo = await Models.EtiquetasModel.Get(mdl); Models.Archivos.Archivos_GetBindingModel model2 = new Models.Archivos.Archivos_GetBindingModel(); model2.ID = IDArchivo; IBuffer buffer = await Models.ArchivosModel.Get(model2); Windows.Data.Pdf.PdfDocument pdf = await Windows.Data.Pdf.PdfDocument.LoadFromStreamAsync(buffer.AsStream().AsRandomAccessStream()); for (uint i = 0; i < pdf.PageCount; i++) { Windows.Data.Pdf.PdfPage page = pdf.GetPage(i); StorageFile bmpFile = await model.DestinationFolder.CreateFileAsync(string.Format("Pagina {0}.bmp", i + 1), CreationCollisionOption.GenerateUniqueName); IRandomAccessStream stream = await bmpFile.OpenAsync(FileAccessMode.ReadWrite); await page.RenderToStreamAsync(stream); await stream.FlushAsync(); stream.Dispose(); page.Dispose(); Utils.SetImageSourceFromFile(bmpFile, DisplayImage); rootPage.NotifyUser("Apertura en progreso...", NotifyType.StatusMessage); Utils.UpdateFileData(bmpFile, model); ScanerListView.SelectedItem = model.FileList.Last(); } rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage); } catch (Exception) { // No pasa nada } finally { model.ScenarioRunning = false; } } else { rootPage.NotifyUser("Debe ingresar primero los datos", NotifyType.ErrorMessage); } }