public void ProcessKeyPress(KeyEventArgs e) { if (false) { } else if (Key.P == e.Key) { PDFAnnotation pdf_annotation = pdf_annotation_node_content.PDFAnnotation.Underlying; PDFDocument pdf_document = pdf_annotation_node_content.PDFDocument.Underlying; int target_resolution = 150; int actual_resolution = target_resolution; double resolution_rescale_factor = 1; Image annotation_image = PDFAnnotationToImageRenderer.RenderAnnotation(pdf_document, pdf_annotation, actual_resolution); BitmapSource cropped_image_page = BitmapImageTools.FromImage(annotation_image, (int)(annotation_image.Width * resolution_rescale_factor), (int)(annotation_image.Height * resolution_rescale_factor)); ImageIcon.Source = cropped_image_page; ImageIcon.Width = cropped_image_page.Width / 2; TextText.MaxWidth = ImageIcon.Width; e.Handled = true; } }
public void RebuildVisual() { //Logging.Info("+HighlightsRenderer RebuildVisual() on page {0}", page); if (null == pdf_document) { Source = null; return; } if (double.IsNaN(Width) || double.IsNaN(Height)) { Source = null; return; } // We use a smaller image than necessary as we do not need high resolution to represent the highlights double scaled_capped_width = Math.Min(Width, 300); double scaled_capped_height = Height * scaled_capped_width / Width; using (Bitmap raster_bitmap = PDFOverlayRenderer.RenderHighlights((int)scaled_capped_width, (int)scaled_capped_height, pdf_document, page)) { Source = BitmapImageTools.FromBitmap(raster_bitmap); } //Logging.Info("-HighlightsRenderer RebuildVisual() on page {0}", page); }
private void DisplayThumbnail() { ImageThumbnail.Source = null; TxtAbstract.Text = ""; if (null == pdf_document) { return; } try { if (pdf_document.DocumentExists) { const double IMAGE_PERCENTAGE = 0.5; using (MemoryStream ms = new MemoryStream(pdf_document.PDFRenderer.GetPageByHeightAsImage(page, ImageThumbnail.Height / IMAGE_PERCENTAGE))) { Bitmap image = (Bitmap)Image.FromStream(ms); PDFOverlayRenderer.RenderAnnotations(image, pdf_document, page, specific_pdf_annotation); PDFOverlayRenderer.RenderHighlights(image, pdf_document, page); PDFOverlayRenderer.RenderInks(image, pdf_document, page); image = image.Clone(new RectangleF { Width = image.Width, Height = (int)Math.Round(image.Height * IMAGE_PERCENTAGE) }, image.PixelFormat); BitmapSource image_page = BitmapImageTools.CreateBitmapSourceFromImage(image); ImageThumbnail.Source = image_page; } } else { string abstract_text = pdf_document.Abstract; if (PDFAbstractExtraction.CANT_LOCATE != abstract_text) { TxtAbstract.Text = abstract_text; } } } catch (Exception ex) { Logging.Error(ex, "There was a problem showing the PDF thumbnail"); } if (null != ImageThumbnail.Source) { ImageThumbnail.Visibility = Visibility.Visible; } else { ImageThumbnail.Visibility = Visibility.Collapsed; } }
public static Image RenderAnnotation(PDFDocument pdf_document, PDFAnnotation pdf_annotation, float dpi) { Image image = Image.FromStream(new MemoryStream(pdf_document.PDFRenderer.GetPageByDPIAsImage(pdf_annotation.Page, dpi))); PDFOverlayRenderer.RenderHighlights(image, pdf_document, pdf_annotation.Page); PDFOverlayRenderer.RenderInks(image, pdf_document, pdf_annotation.Page); // We rescale in the Drawing.Bitmap world because the WPF world uses so much memory Image cropped_image = BitmapImageTools.CropImageRegion(image, pdf_annotation.Left, pdf_annotation.Top, pdf_annotation.Width, pdf_annotation.Height); return(cropped_image); }
private static BitmapSource GetSnappedImage(DocPageInfo page_info, Point mouse_up_point, Point mouse_down_point) { WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread(); BitmapSource cropped_image_page = null; using (MemoryStream ms = new MemoryStream(page_info.pdf_document.GetPageByDPIAsImage(page_info.page, 150))) { PngBitmapDecoder decoder = new PngBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); BitmapSource image_page = decoder.Frames[0]; if (null != image_page) { double left = Math.Min(mouse_up_point.X, mouse_down_point.X) * image_page.PixelWidth / page_info.ActualWidth; double top = Math.Min(mouse_up_point.Y, mouse_down_point.Y) * image_page.PixelHeight / page_info.ActualHeight; double width = Math.Abs(mouse_up_point.X - mouse_down_point.X) * image_page.PixelWidth / page_info.ActualWidth; double height = Math.Abs(mouse_up_point.Y - mouse_down_point.Y) * image_page.PixelHeight / page_info.ActualHeight; left = Math.Max(left, 0); top = Math.Max(top, 0); width = Math.Min(width, image_page.PixelWidth - left); height = Math.Min(height, image_page.PixelHeight - top); if (0 < width && 0 < height) { var cropped = new CroppedBitmap(image_page, new Int32Rect((int)left, (int)top, (int)width, (int)height)); // UPDATE HERE: CroppedBitmap to BitmapImage // cropped_image_page = GetJpgImage(cropped.Source); // or //cropped_image_page = GetPngImage(cropped.Source); using (MemoryStream mStream = new MemoryStream()) { PngBitmapEncoder jEncoder = new PngBitmapEncoder(); jEncoder.Frames.Add(BitmapFrame.Create(cropped)); // the croppedBitmap is a CroppedBitmap object // jEncoder.QualityLevel = 75; jEncoder.Save(mStream); cropped_image_page = BitmapImageTools.LoadFromStream(mStream); // I can also get array of bytes that represent the cropped image by call this method : mStream.GetBuffer() //cropped_image_page = BitmapImageTools.CropImageRegion(image_page, left, top, width, height); } } } return(cropped_image_page); } }
public static Image RenderAnnotation(PDFDocument pdf_document, PDFAnnotation pdf_annotation, int dpi) { WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread(); using (MemoryStream ms = new MemoryStream(pdf_document.GetPageByDPIAsImage(pdf_annotation.Page, dpi))) { Image image = Image.FromStream(ms); PDFOverlayRenderer.RenderHighlights(image, pdf_document, pdf_annotation.Page); PDFOverlayRenderer.RenderInks(image, pdf_document, pdf_annotation.Page); // We rescale in the Drawing.Bitmap world because the WPF world uses so much memory Image cropped_image = BitmapImageTools.CropImageRegion(image, pdf_annotation.Left, pdf_annotation.Top, pdf_annotation.Width, pdf_annotation.Height); return(cropped_image); } }
public override DocumentPage GetPage(int page_zero_based) { // Hackity hack WPFDoEvents.DoEvents(); if (null != last_document_page) { last_document_page.Dispose(); last_document_page = null; } int page = page_from + page_zero_based; StatusManager.Instance.UpdateStatus("PDFPrinter", String.Format("Printing page {0} of {1}", page_zero_based + 1, this.PageCount), page_zero_based + 1, this.PageCount, true); // Render a page at 300 DPI... using (Image image = Image.FromStream(new MemoryStream(pdf_renderer.GetPageByDPIAsImage(page, 300)))) { PDFOverlayRenderer.RenderAnnotations(image, pdf_document, page, null); PDFOverlayRenderer.RenderHighlights(image, pdf_document, page); PDFOverlayRenderer.RenderInks(image, pdf_document, page); BitmapSource image_page = BitmapImageTools.CreateBitmapSourceFromImage(image); image_page.Freeze(); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { // Rotate the image if its orientation does not match the printer if ( page_size.Width < page_size.Height && image_page.Width > image_page.Height || page_size.Width > page_size.Height && image_page.Width < image_page.Height ) { image_page = new TransformedBitmap(image_page, new RotateTransform(90)); image_page.Freeze(); } dc.DrawImage(image_page, new Rect(0, 0, page_size.Width, page_size.Height)); } ++total_pages_printed; last_document_page = new DocumentPage(dv); return(last_document_page); } }
void ObjButtonGO_Click(object sender, RoutedEventArgs e) { int pdf_number = Convert.ToInt32(ObjTextDoc.Text); int page_number = Convert.ToInt32(ObjTextPage.Text); string pdf_filename = String.Format(@"C:\temp\{0}.pdf", pdf_number); Logging.Info("+Rendering page"); MemoryStream ms = MuPDFRenderer.RenderPDFPage(pdf_filename, page_number, 200, null, ProcessPriorityClass.Normal); BitmapSource bitmap_image = BitmapImageTools.LoadFromBytes(ms.ToArray()); Bitmap bitmap = new Bitmap(ms); Logging.Info("-Rendering page"); this.Image = bitmap_image; Logging.Info("+Finding regions"); this.region_locator = new PDFRegionLocator(bitmap); Logging.Info("-Finding regions"); Recalc(); }
public void RebuildVisual() { WPFDoEvents.AssertThisCodeIsRunningInTheUIThread(); //Logging.Info("+HighlightsRenderer RebuildVisual() on page {0}", page); if (null == pdf_document) { Source = null; return; } if (double.IsNaN(Width) || double.IsNaN(Height)) { Source = null; return; } // We use a smaller image than necessary as we do not need high resolution to represent the highlights double scaled_capped_width = Math.Min(Width, 300); double scaled_capped_height = Height * scaled_capped_width / Width; SafeThreadPool.QueueUserWorkItem(o => { BitmapSource bmp; using (Bitmap raster_bitmap = PDFOverlayRenderer.RenderHighlights((int)scaled_capped_width, (int)scaled_capped_height, pdf_document, page)) { bmp = BitmapImageTools.FromBitmap(raster_bitmap); } WPFDoEvents.InvokeAsyncInUIThread(() => { Source = bmp; }); //Logging.Info("-HighlightsRenderer RebuildVisual() on page {0}", page); }); }
private static PageContent generatePageContent( Bitmap bitmap, int top, int bottom, double pageWidth, double PageHeight, PrintCapabilities capabilities ) { FixedPage printDocumentPage = new FixedPage(); printDocumentPage.Width = pageWidth; printDocumentPage.Height = PageHeight; int newImageHeight = bottom - top; Bitmap bmpPage = BitmapImageTools.CropBitmapRegion(bitmap, 0, top, bitmap.Width, newImageHeight); BitmapSource bmpSource = BitmapImageTools.FromBitmap(bmpPage); // Create a new bitmap for the contents of this page Image pageImage = new Image(); pageImage.Source = bmpSource; pageImage.VerticalAlignment = VerticalAlignment.Center; // Place the bitmap on the page printDocumentPage.Children.Add(pageImage); PageContent pageContent = new PageContent(); ((IAddChild)pageContent).AddChild(printDocumentPage); pageImage.Width = capabilities.PageImageableArea.ExtentWidth; pageImage.Height = capabilities.PageImageableArea.ExtentHeight; FixedPage.SetLeft(pageImage, capabilities.PageImageableArea.OriginWidth); FixedPage.SetTop(pageImage, capabilities.PageImageableArea.OriginHeight); return(pageContent); }
public static void TestHarness_TEXT_RENDER_ONE(string PDF_FILENAME, int PAGE) { SolidColorBrush BRUSH_EDGE = new SolidColorBrush(Colors.Red); SolidColorBrush BRUSH_BACKGROUND = new SolidColorBrush(ColorTools.MakeTransparentColor(Colors.GreenYellow, 64)); // Load the image graphic MemoryStream ms = RenderPDFPage(PDF_FILENAME, PAGE, 150, null, ProcessPriorityClass.Normal); BitmapSource bitmap_image = BitmapImageTools.LoadFromBytes(ms.ToArray()); Image image = new Image(); image.Source = bitmap_image; image.Stretch = Stretch.Fill; // Load the image text Canvas canvas = new Canvas(); List <TextChunk> text_chunks = GetEmbeddedText(PDF_FILENAME, "" + PAGE, null, ProcessPriorityClass.Normal); List <Rectangle> rectangles = new List <Rectangle>(); foreach (TextChunk text_chunk in text_chunks) { Rectangle rectangle = new Rectangle(); rectangle.Stroke = BRUSH_EDGE; rectangle.Fill = BRUSH_BACKGROUND; rectangle.Tag = text_chunk; rectangles.Add(rectangle); canvas.Children.Add(rectangle); } RectanglesManager rm = new RectanglesManager(rectangles, canvas); Grid grid = new Grid(); grid.Children.Add(image); grid.Children.Add(canvas); ControlHostingWindow window = new ControlHostingWindow("PDF", grid); window.Show(); }
private void UpdateLibraryStatistics_Stats_Background_CoverFlow() { // The list of recommended items DocumentDisplayWorkManager ddwm = new DocumentDisplayWorkManager(); { { int ITEMS_IN_LIST = 5; // Upcoming reading is: // interrupted // top priority // read again // recently added and no status List <PDFDocument> pdf_documents_all = web_library_detail.library.PDFDocuments; pdf_documents_all.Sort(PDFDocumentListSorters.DateAddedToDatabase); foreach (string reading_stage in new string[] { Choices.ReadingStages_INTERRUPTED, Choices.ReadingStages_TOP_PRIORITY, Choices.ReadingStages_READ_AGAIN }) { foreach (PDFDocument pdf_document in pdf_documents_all) { if (!pdf_document.DocumentExists) { continue; } if (pdf_document.ReadingStage == reading_stage) { if (!ddwm.ContainsPDFDocument(pdf_document)) { ddwm.AddDocumentDisplayWork(DocumentDisplayWork.StarburstColor.Pink, reading_stage, pdf_document); if (ddwm.Count >= ITEMS_IN_LIST) { break; } } } } } } { int ITEMS_IN_LIST = 3; // Recently added { List <PDFDocument> pdf_documents = web_library_detail.library.PDFDocuments; pdf_documents.Sort(PDFDocumentListSorters.DateAddedToDatabase); int num_added = 0; foreach (PDFDocument pdf_document in pdf_documents) { if (!pdf_document.DocumentExists) { continue; } if (!ddwm.ContainsPDFDocument(pdf_document)) { ddwm.AddDocumentDisplayWork(DocumentDisplayWork.StarburstColor.Green, "Added Recently", pdf_document); if (++num_added >= ITEMS_IN_LIST) { break; } } } } // Recently read { List <PDFDocument> pdf_documents = web_library_detail.library.PDFDocuments; pdf_documents.Sort(PDFDocumentListSorters.DateLastRead); int num_added = 0; foreach (PDFDocument pdf_document in pdf_documents) { if (!pdf_document.DocumentExists) { continue; } if (!ddwm.ContainsPDFDocument(pdf_document)) { ddwm.AddDocumentDisplayWork(DocumentDisplayWork.StarburstColor.Blue, "Read Recently", pdf_document); if (++num_added >= ITEMS_IN_LIST) { break; } } } } } // And fill the placeholders WPFDoEvents.InvokeInUIThread(() => UpdateLibraryStatistics_Stats_Background_GUI_AddAllPlaceHolders(ddwm.ddws)); // Now render each document using (Font font = new Font("Times New Roman", 11.0f)) { using (StringFormat string_format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }) { var color_matrix = new ColorMatrix(); color_matrix.Matrix33 = 0.9f; using (var image_attributes = new ImageAttributes()) { image_attributes.SetColorMatrix(color_matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); foreach (DocumentDisplayWork ddw in ddwm.ddws) { try { using (MemoryStream ms = new MemoryStream(ddw.pdf_document.PDFRenderer.GetPageByHeightAsImage(1, PREVIEW_IMAGE_HEIGHT / PREVIEW_IMAGE_PERCENTAGE))) { Bitmap page_bitmap = (Bitmap)System.Drawing.Image.FromStream(ms); page_bitmap = page_bitmap.Clone(new RectangleF { Width = page_bitmap.Width, Height = (int)Math.Round(page_bitmap.Height * PREVIEW_IMAGE_PERCENTAGE) }, page_bitmap.PixelFormat); using (Graphics g = Graphics.FromImage(page_bitmap)) { int CENTER = 60; int RADIUS = 60; { BitmapImage starburst_bi = null; switch (ddw.starburst_color) { case DocumentDisplayWork.StarburstColor.Blue: starburst_bi = Icons.GetAppIcon(Icons.PageCornerBlue); break; case DocumentDisplayWork.StarburstColor.Green: starburst_bi = Icons.GetAppIcon(Icons.PageCornerGreen); break; case DocumentDisplayWork.StarburstColor.Pink: starburst_bi = Icons.GetAppIcon(Icons.PageCornerPink); break; default: starburst_bi = Icons.GetAppIcon(Icons.PageCornerOrange); break; } Bitmap starburst_image = BitmapImageTools.ConvertBitmapSourceToBitmap(starburst_bi); g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawImage( starburst_image, new Rectangle(CENTER - RADIUS, CENTER - RADIUS, 2 * RADIUS, 2 * RADIUS), 0, 0, starburst_image.Width, starburst_image.Height, GraphicsUnit.Pixel, image_attributes ); } using (Matrix mat = new Matrix()) { mat.RotateAt(-50, new PointF(CENTER / 2, CENTER / 2)); g.Transform = mat; string wrapped_caption = ddw.starburst_caption; wrapped_caption = wrapped_caption.ToLower(); wrapped_caption = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(wrapped_caption); wrapped_caption = wrapped_caption.Replace(" ", "\n"); g.DrawString(wrapped_caption, font, Brushes.Black, new PointF(CENTER / 2, CENTER / 2), string_format); } } BitmapSource page_bitmap_source = BitmapImageTools.CreateBitmapSourceFromImage(page_bitmap); ddw.page_bitmap_source = page_bitmap_source; } WPFDoEvents.InvokeInUIThread(() => UpdateLibraryStatistics_Stats_Background_GUI_FillPlaceHolder(ddw)); } catch (Exception ex) { Logging.Warn(ex, "There was a problem loading a preview image for document {0}", ddw.pdf_document.Fingerprint); } } } } } if (0 == ddwm.ddws.Count) { WPFDoEvents.InvokeAsyncInUIThread(() => { ButtonCoverFlow.IsChecked = false; UpdateLibraryStatistics(); } ); } } }
private void UpdateLibraryStatistics_Headers() { WPFDoEvents.AssertThisCodeIsRunningInTheUIThread(); TextLibraryCount.Text = ""; PanelForHyperlinks.Visibility = Visibility.Visible; PanelForget.Visibility = Visibility.Collapsed; PanelSetSyncPoint.Visibility = Visibility.Collapsed; PanelLocateSyncPoint.Visibility = Visibility.Collapsed; PanelEdit.Visibility = Visibility.Collapsed; PanelDelete.Visibility = Visibility.Collapsed; PanelPurge.Visibility = Visibility.Collapsed; ButtonAutoSync.Visibility = Visibility.Collapsed; ButtonReadOnly.Visibility = Visibility.Collapsed; ObjTitleImage.Source = null; // Store the web library details WebLibraryDetail web_library_detail = DataContext as WebLibraryDetail; // No need to wait until the library has been completely loaded! drag_to_library_manager.DefaultLibrary = web_library_detail; if (null != web_library_detail) { if (!web_library_detail.IsIntranetLibrary) { TextLibraryCount.Text = String.Format("{0} document(s) in this library", web_library_detail.Xlibrary?.PDFDocuments_IncludingDeleted_Count ?? 0); } else { TextLibraryCount.Text = String.Format("{0} document(s) in this library, {1}", web_library_detail.Xlibrary?.PDFDocuments_IncludingDeleted_Count ?? 0, web_library_detail.LastSynced.HasValue ? $"which was last synced on {web_library_detail.LastSynced.Value}" : @"which has never been synced yet"); } // The wizard stuff if (ConfigurationManager.Instance.ConfigurationRecord.GUI_IsNovice) { WizardDPs.SetPointOfInterest(ButtonIcon, "GuestLibraryOpenButton"); WizardDPs.SetPointOfInterest(TxtTitle, "GuestLibraryTitle"); } // The icon stuff { RenderOptions.SetBitmapScalingMode(ButtonIcon, BitmapScalingMode.HighQuality); ButtonIcon.Width = 64; ButtonIcon.Height = 64; if (web_library_detail.IsIntranetLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeWeb); //ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeIntranet); ButtonIcon.ToolTip = "This is an Intranet Library.\nYou can sync it via your Intranet to share with colleagues and across your company computers. Alternatively you can sync to a folder in Cloud Storage such as DropBox, Google Drive or Microsoft OneDrive and anyone with access to that shared folder can sync with your library."; } else if (web_library_detail.IsBundleLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeBundle); ButtonIcon.ToolTip = "This is a Bundle Library.\nIt's contents will be updated automatically when the Bundle is updated by it's administrator."; } else { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeGuest); ButtonIcon.ToolTip = "This is a local Library.\nIts contents are local to this computer. When you assign this library a Sync Point, it can be synchronized with that backup location and possibly shared with other people and machines."; } } // The customization images stuff { string image_filename = CustomBackgroundFilename(); if (File.Exists(image_filename)) { try { ObjTitleImage.Source = BitmapImageTools.FromImage(ImageLoader.Load(image_filename)); } catch (Exception ex) { Logging.Warn(ex, "Problem with custom library background."); } } } { string image_filename = CustomIconFilename(); if (File.Exists(image_filename)) { try { ButtonIcon.Source = BitmapImageTools.FromImage(ImageLoader.Load(image_filename)); } catch (Exception ex) { Logging.Warn(ex, "Problem with custom library icon."); } } } // The autosync stuff if (web_library_detail.IsIntranetLibrary) { ButtonAutoSync.Visibility = Visibility.Visible; ButtonAutoSync.IsChecked = web_library_detail.AutoSync; } // The readonly stuff if (web_library_detail.IsReadOnlyLibrary) { ButtonReadOnly.Visibility = Visibility.Visible; } // The hyperlinks panel PanelEdit.Visibility = Visibility.Visible; PanelDelete.Visibility = Visibility.Visible; PanelForget.Visibility = Visibility.Visible; //PanelSetSyncPoint.Visibility = Visibility.Visible; //PanelLocateSyncPoint.Visibility = Visibility.Visible; PanelEdit.Visibility = Visibility.Visible; PanelDelete.Visibility = Visibility.Visible; //PanelPurge.Visibility = Visibility.Visible; if (web_library_detail.Deleted) { PanelPurge.Visibility = Visibility.Visible; } if (web_library_detail.IsIntranetLibrary) { PanelLocateSyncPoint.Visibility = Visibility.Visible; } if (!web_library_detail.IsReadOnlyLibrary) { PanelSetSyncPoint.Visibility = Visibility.Visible; } } }
private static void BackgroundRenderImages_BACKGROUND(FlowDocument flow_document, List <AnnotationWorkGenerator.AnnotationWork> annotation_works, AnnotationReportOptions annotation_report_options) { Thread.Sleep(annotation_report_options.InitialRenderDelayMilliseconds); PDFDocument last_pdf_document = null; StatusManager.Instance.ClearCancelled("AnnotationReportBackground"); for (int j = 0; j < annotation_works.Count; ++j) { StatusManager.Instance.UpdateStatus("AnnotationReportBackground", "Building annotation report image", j, annotation_works.Count, true); if (StatusManager.Instance.IsCancelled("AnnotationReportBackground")) { Logging.Warn("User cancelled annotation report generation"); break; } AnnotationWorkGenerator.AnnotationWork annotation_work = annotation_works[j]; PDFDocument pdf_document = annotation_work.pdf_document; // Clear down our previously caches pages if (null != last_pdf_document && last_pdf_document != pdf_document) { if (last_pdf_document.DocumentExists) { last_pdf_document.PDFRenderer.FlushCachedPageRenderings(); } } // Remember this PDF document so we can flush it if necessary last_pdf_document = pdf_document; // Now render each image PDFAnnotation pdf_annotation = annotation_work.pdf_annotation; if (null != pdf_annotation) { try { // Clear the waiting for processing text annotation_work.processing_error.Dispatcher.Invoke(new Action(() => { annotation_work.processing_error.Text = ""; } ), DispatcherPriority.Background); if (pdf_document.DocumentExists) { // Fill in the paragraph text if (null != annotation_work.annotation_paragraph) { annotation_work.processing_error.Dispatcher.Invoke( new Action(() => BuildAnnotationWork_FillAnnotationText(pdf_document, pdf_annotation, annotation_work)), DispatcherPriority.Background); } if (null != annotation_work.report_floater) { annotation_work.processing_error.Dispatcher.Invoke(new Action(() => { try { System.Drawing.Image annotation_image = PDFAnnotationToImageRenderer.RenderAnnotation(pdf_document, pdf_annotation, 80); BitmapSource cropped_image_page = BitmapImageTools.FromImage(annotation_image); annotation_work.report_image.Source = cropped_image_page; annotation_work.report_floater.Width = new FigureLength(cropped_image_page.PixelWidth / 1); } catch (Exception ex) { Logging.Warn(ex, "There was a problem while rendering an annotation."); annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); annotation_work.processing_error.Text = "There was a problem while rendering this annotation."; } } ), DispatcherPriority.Background); } } else { annotation_work.processing_error.Dispatcher.Invoke(new Action(() => { if (null != annotation_work.report_image) { annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); } annotation_work.processing_error.Text = "Can't show image: The PDF does not exist locally."; } ), DispatcherPriority.Background); } } catch (Exception ex) { Logging.Error(ex, "There was an error while rendering page {0} for document {1} for the annotation report", pdf_annotation.Page, pdf_annotation.DocumentFingerprint); annotation_work.processing_error.Dispatcher.Invoke(new Action(() => { if (null != annotation_work.report_image) { annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); } annotation_work.processing_error.Text = "Can't show image: There was an error rendering the metadata image."; } ), DispatcherPriority.Background); } } } // And flush the rendering cache of the last document if (null != last_pdf_document) { if (last_pdf_document.DocumentExists) { last_pdf_document.PDFRenderer.FlushCachedPageRenderings(); } } StatusManager.Instance.ClearStatus("AnnotationReportBackground"); }
public static void PrintMultipage(FrameworkElement objectToPrint, string print_job_name) { double original_width = objectToPrint.ActualWidth; double original_height = objectToPrint.ActualHeight; PrintDialog printDialog = new PrintDialog(); if ((bool)printDialog.ShowDialog().GetValueOrDefault()) { PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket); double DPI = 200; double dpiScale = DPI / 96.0; FixedDocument document = new FixedDocument(); document.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); // Convert the UI control into a bitmap at 300 dpi RenderTargetBitmap bmp = new RenderTargetBitmap( Convert.ToInt32(objectToPrint.ActualWidth * dpiScale), Convert.ToInt32(objectToPrint.ActualHeight * dpiScale), DPI, DPI, PixelFormats.Pbgra32 ); bmp.Render(objectToPrint); bmp.Freeze(); // Convert the RenderTargetBitmap into a bitmap we can more readily use Bitmap bmp2 = BitmapImageTools.ConvertBitmapSourceToBitmap(bmp); bmp = null; // Break the bitmap down into pages int pageWidth = Convert.ToInt32(capabilities.PageImageableArea.ExtentWidth * dpiScale); int pageHeight = Convert.ToInt32(capabilities.PageImageableArea.ExtentHeight * dpiScale); int bmp_width = bmp2.Width; int bmp_height = (int)(pageHeight * bmp2.Width / pageWidth); int pageBreak = 0; int previousPageBreak = 0; while (true) { pageBreak += bmp_height; // We can't read out more than the image if (pageBreak > bmp2.Height) { pageBreak = bmp2.Height; } PageContent pageContent = generatePageContent( bmp2, previousPageBreak, pageBreak, document.DocumentPaginator.PageSize.Width, document.DocumentPaginator.PageSize.Height, capabilities ); document.Pages.Add(pageContent); previousPageBreak = pageBreak; // Are we done? if (pageBreak >= bmp2.Height) { break; } } printDialog.PrintDocument(document.DocumentPaginator, print_job_name); } }
public static StandardFlowDocument DoExport(PDFDocument pdf_document) { StandardFlowDocument flow_document = new StandardFlowDocument(); flow_document.Background = Brushes.White; using (AugmentedPdfLoadedDocument doc = new AugmentedPdfLoadedDocument(pdf_document.DocumentPath)) { for (int page = 1; page <= pdf_document.PageCount; ++page) { string msg = $"Exporting page {page}/{pdf_document.PageCountAsString}"; StatusManager.Instance.UpdateStatus("ExportToWord", msg, page, Math.Max(1, pdf_document.PageCount)); try { Logging.Info(msg); // Add the header for the page { Bold bold = new Bold(); bold.Inlines.Add(String.Format("--- Page {0} ---", page)); flow_document.Blocks.Add(new Paragraph(bold)); } StringBuilder sb = new StringBuilder(); WordList words = pdf_document.GetOCRText(page); if (null != words) { Word last_word = null; foreach (Word word in words) { // Add a newline if we seem to have a linebreak if ( ( (null != last_word && last_word.Left > word.Left) && (word.Top > last_word.Top + 2 * last_word.Height) && (word.Text.Length > 0 && !Char.IsLower(word.Text[0])) ) || ( (null != last_word && last_word.Left > word.Left) && (word.Top > last_word.Top + 2.5 * last_word.Height) ) ) { sb.Append("\n\n"); } sb.Append(word.Text); sb.Append(' '); last_word = word; } } else { sb.AppendLine(String.Format("OCR text is not yet ready for page {0}. Please try again in a few minutes.", page)); } // Add the text from the page { Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(sb.ToString()); flow_document.Blocks.Add(paragraph); } // Add the images from the page PdfPageBase pdf_page = doc.Pages[page - 1]; Image[] images = pdf_page.ExtractImages(); if (null != images) { foreach (Image image in images) { BitmapSource bitmap_source = BitmapImageTools.FromImage(image); System.Windows.Controls.Image image_to_render = new System.Windows.Controls.Image(); image_to_render.Source = bitmap_source; BlockUIContainer image_container = new BlockUIContainer(image_to_render); Figure floater = new Figure(image_container); floater.HorizontalAnchor = FigureHorizontalAnchor.PageLeft; floater.WrapDirection = WrapDirection.None; floater.Width = new FigureLength(image.Width); { Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(floater); flow_document.Blocks.Add(paragraph); } } } // Add the annotations from the page #if false { Logging.Debug("This PDF has {0} annotations", pdf_page.Annotations.Count); Logging.Debug("The size of the page is {0}", pdf_page.Size); foreach (var annotation in pdf_page.Annotations) { PdfLoadedUriAnnotation uri_annotation = annotation as PdfLoadedUriAnnotation; if (null != uri_annotation) { Logging.Debug("There is a URL to '{0}' with text '{1}' with bounds '{2}'", uri_annotation.Uri, uri_annotation.Bounds, uri_annotation.Text, null); } } } #endif } catch (Exception ex) { Logging.Error(ex, "There was a problem exporting page {0}", page); } } } StatusManager.Instance.UpdateStatus("ExportToWord", "Finished exporting"); return(flow_document); }
private void UpdateLibraryStatistics_Headers() { TextLibraryCount.Text = ""; PanelForHyperlinks.Visibility = Visibility.Collapsed; PanelForget.Visibility = Visibility.Collapsed; PanelLocateSyncPoint.Visibility = Visibility.Collapsed; PanelViewOnline.Visibility = Visibility.Collapsed; PanelInviteAndShare.Visibility = Visibility.Collapsed; PanelEditDelete.Visibility = Visibility.Collapsed; PanelTopUp.Visibility = Visibility.Collapsed; PanelPurge.Visibility = Visibility.Collapsed; ButtonAutoSync.Visibility = Visibility.Collapsed; ButtonReadOnly.Visibility = Visibility.Collapsed; if (null != web_library_detail) { TextLibraryCount.Text = String.Format("{0} document(s) in this library", web_library_detail.library.PDFDocuments_IncludingDeleted_Count); //TextLibraryCount.Text = // String.Format( // " ({0} documents, last synced on {1})", // web_library_detail.library.PDFDocuments.Count, // web_library_detail.LastSynced.HasValue ? web_library_detail.LastSynced.Value.ToString() : "Never" // ); // The wizard stuff if (web_library_detail.IsLocalGuestLibrary) { WizardDPs.SetPointOfInterest(ButtonIcon, "GuestLibraryOpenButton"); WizardDPs.SetPointOfInterest(TxtTitle, "GuestLibraryTitle"); } // The icon stuff { RenderOptions.SetBitmapScalingMode(ButtonIcon, BitmapScalingMode.HighQuality); ButtonIcon.Width = 64; ButtonIcon.Height = 64; if (web_library_detail.IsWebLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeWeb); ButtonIcon.ToolTip = "This is a Web Library.\nYou can sync it via the cloud to access it online or on your other devices."; } else if (web_library_detail.IsIntranetLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeIntranet); ButtonIcon.ToolTip = "This is an Intranet Library.\nYou can sync it via your Intranet to share with colleagues and across your company computers."; } else if (web_library_detail.IsLocalGuestLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeGuest); ButtonIcon.ToolTip = "This is a Guest Library.\nIts contents remain local to this computer and can not be synced."; } else if (web_library_detail.IsBundleLibrary) { ButtonIcon.Source = Icons.GetAppIcon(Icons.LibraryTypeBundle); ButtonIcon.ToolTip = "This is a Bundle Library.\nIt's contents will be updated automatically when the Bundle is updates by it's administrator."; } else { ButtonIcon.Source = null; ButtonIcon.ToolTip = null; } } // The customization images stuff { string image_filename = CustomBackgroundFilename; if (File.Exists(image_filename)) { try { ObjTitleImage.Source = BitmapImageTools.FromImage(ImageLoader.Load(image_filename)); } catch (Exception ex) { Logging.Warn(ex, "Problem with custom library background."); } } else { ObjTitleImage.Source = null; } } { string image_filename = CustomIconFilename; if (File.Exists(image_filename)) { try { ButtonIcon.Source = BitmapImageTools.FromImage(ImageLoader.Load(image_filename)); } catch (Exception ex) { Logging.Warn(ex, "Problem with custom library icon."); } } } // The autosync stuff if (web_library_detail.IsWebLibrary || web_library_detail.IsIntranetLibrary) { ButtonAutoSync.Visibility = Visibility.Visible; ButtonAutoSync.IsChecked = web_library_detail.AutoSync; } // The readonly stuff if (web_library_detail.IsReadOnly) { ButtonReadOnly.Visibility = Visibility.Visible; } // The hyperlinks panel if (web_library_detail.IsWebLibrary) { PanelForHyperlinks.Visibility = Visibility.Visible; PanelViewOnline.Visibility = Visibility.Visible; PanelTopUp.Visibility = Visibility.Visible; if (web_library_detail.IsAdministrator) { PanelInviteAndShare.Visibility = Visibility.Visible; PanelEditDelete.Visibility = Visibility.Visible; } if (web_library_detail.Deleted) { PanelPurge.Visibility = Visibility.Visible; } } if (web_library_detail.IsIntranetLibrary) { PanelForHyperlinks.Visibility = Visibility.Visible; PanelForget.Visibility = Visibility.Visible; PanelLocateSyncPoint.Visibility = Visibility.Visible; } if (web_library_detail.IsBundleLibrary) { PanelForHyperlinks.Visibility = Visibility.Visible; PanelForget.Visibility = Visibility.Visible; } } }