Class PdfViewer
- All Implemented Interfaces:
Animation, Editable, StyleListener
Displays a PDF document: pages stacked vertically and scrolled continuously, fitted to the width of the component and zoomed by pinch or double tap.
Pages are drawn by a pure-Java renderer, so a document looks the same on every platform and needs no native viewer:
PdfDocument doc = new PdfDocument();
for (int i = 1; i <= 5; i++) {
doc.addPage(PdfPageSize.A4).getCanvas().drawText("Page " + i, 72, 72);
}
byte[] pdfBytes = doc.toByteArray();
Form form = new Form("Document", new BorderLayout());
PdfViewer viewer = new PdfViewer(pdfBytes);
form.add(BorderLayout.CENTER, viewer);
viewer.setPage(3);
Pages render one at a time on the EDT, interleaved with other events, and only the pages near the view are kept as images. A page that is not drawn yet shows as a blank sheet.
The renderer covers vector graphics with dashes, blend modes, transparency and knockout groups and soft masks; every shading type; embedded TrueType, OpenType, CFF, Type 1 and Type 3 fonts, horizontal and vertical; images in every PDF filter, JPEG 2000, JBIG2 and CCITT fax included; and annotation appearances. Fonts that are not embedded are drawn with a platform font of the same family, so their shapes differ from the original.
-
Field Summary
Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected DimensionCalculates the preferred size based on component content.protected voidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.intgetPage()The page at the middle of the view, zero based.intThe number of pages.floatgetZoom()The zoom factor, 1 when a page fits the width.booleanIndicates whether the component should/could scroll on the X axisbooleanIndicates whether the component should/could scroll on the Y axisprotected voidlaidOut()This is a callback method to inform the Component when it's been laidout on the parent Containerstatic PdfVieweropen(InputStream in) A viewer for the PDF read fromin, which is closed.voidThis method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.protected booleanpinch(float scale) Invoked by subclasses interested in handling pinch to zoom events, if true is returned other drag events will not be broadcastprotected voidpinchReleased(int x, int y) To be implemented by subclasses interested in being notified when a pinch zoom has ended (i.e the user has removed one of their fingers, but is still dragging).voidpointerReleased(int x, int y) If this Component is focused, the pointer released event will call this methodrenderPage(int index, double scale) Renders pageindex(zero based) to an image atscalepixels per point, white background, annotations included.voidsetPage(int index) Scrolls so that pageindex(zero based) is at the top of the view.voidsetZoom(float z) Sets the zoom factor, clamped to 1..5, keeping the middle of the view in place.Methods inherited from class Component
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addNativeDragOverListener, addNativeDropListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, canAcceptNativeDrop, cancelRepaints, clearClientProperties, consumesRawTextInput, contains, containsOrOwns, createNativeDragOperation, createStyleAnimation, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAcceptedDropActions, getAcceptedDropMimeTypes, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBottomGap, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getContextMenuCommands, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getGridPosX, getGridPosY, getHeight, getHoverStyle, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeDragOperation, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getSideGap, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initComponent, initCustomStyle, initDisabledStyle, initLaf, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHovered, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isNativeDragSource, isNativeDropTarget, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSelectableInteraction, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyPressed, keyReleased, keyRepeated, longKeyPress, longPointerPress, mouseWheel, nativeDragEnter, nativeDragExit, nativeDragOver, nativeDrop, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, paramString, parsePreferredSize, pinch, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerPressed, pointerReleased, putClientProperty, refreshTheme, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removeNativeDragOverListener, removeNativeDropListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAcceptedDropActions, setAcceptedDropMimeTypes, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setContextMenuCommands, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setHovered, setHoverStyle, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNativeDragOperation, setNativeDragSource, setNativeDropTarget, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stopScrollMomentum, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
PdfViewer
A viewer for the PDF in
data.Throws
IOException: when the data is not a PDF, or it is encrypted with a user password.
- Throws:
IOException
-
PdfViewer
A viewer for the PDF in
data, opened withpassword(the user or the owner password) when it is encrypted.Throws
IOException: when the data is not a PDF or the password is wrong.
- Throws:
IOException
-
-
Method Details
-
open
A viewer for the PDF read from
in, which is closed.Throws
IOException: when reading fails or the data is not a PDF.
- Throws:
IOException
-
getPageCount
public int getPageCount()The number of pages. -
getZoom
public float getZoom()The zoom factor, 1 when a page fits the width. -
setZoom
public void setZoom(float z) Sets the zoom factor, clamped to 1..5, keeping the middle of the view in place. -
getPage
public int getPage()The page at the middle of the view, zero based. -
setPage
public void setPage(int index) Scrolls so that pageindex(zero based) is at the top of the view. -
renderPage
Renders pageindex(zero based) to an image atscalepixels per point, white background, annotations included. Usable without showing the viewer, for a thumbnail or a share sheet. -
isScrollableY
public boolean isScrollableY()Description copied from class:ComponentIndicates whether the component should/could scroll on the Y axis
Returns
whether the component is scrollable on the X axis
- Overrides:
isScrollableYin classComponent
-
isScrollableX
public boolean isScrollableX()Description copied from class:ComponentIndicates whether the component should/could scroll on the X axis
Returns
whether the component is scrollable on the X axis
- Overrides:
isScrollableXin classComponent
-
calcPreferredSize
Description copied from class:ComponentCalculates the preferred size based on component content. This method is invoked lazily by getPreferred size.
Returns
the calculated preferred size based on component content
- Overrides:
calcPreferredSizein classComponent
-
laidOut
-
paint
Description copied from class:ComponentThis method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.
Parameters
g: the component graphics
-
pinch
protected boolean pinch(float scale) Description copied from class:ComponentInvoked by subclasses interested in handling pinch to zoom events, if true is returned other drag events will not be broadcast
Parameters
scale: @param scale the scaling of the pinch operation a number larger than 1 means scaling up and smaller than 1 means scaling down. It is recommended that code would threshold the number (so a change between 1.0 and 1.02 shouldn't necessarily trigger zoom). Notice that this number is relevant to current zoom levels and unaware of them so you should also enforce limits of maximum/minimum zoom levels.
Returns
false by default
-
pinchReleased
protected void pinchReleased(int x, int y) Description copied from class:ComponentTo be implemented by subclasses interested in being notified when a pinch zoom has ended (i.e the user has removed one of their fingers, but is still dragging).
Parameters
-
x: The x-coordinate of the remaining finger in the drag. (Absolute) -
y: The y-coordinate of the remaining finger in the drag. (Absolute)
- Overrides:
pinchReleasedin classComponent
-
-
pointerReleased
public void pointerReleased(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer released event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerReleasedin classComponent
-
-
deinitialize
protected void deinitialize()Description copied from class:ComponentInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.- Overrides:
deinitializein classComponent
-