Client API. The Codename One framework your app is built on: this runs on the device, not in a backend.
public class PdfViewer
ImplementsAnimation, 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.
Constructors
public PdfViewer(byte[] data)
throws IOException | A viewer for the PDF in data. |
public PdfViewer(byte[] data, String password)
throws IOException | A viewer for the PDF in data, opened with password (the user or the owner password) when it is encrypted. |
Methods
public static PdfViewer open(InputStream in)
throws IOException | A viewer for the PDF read from in, which is closed. |
public int getPageCount() | The number of pages. |
public float getZoom() | The zoom factor, 1 when a page fits the width. |
public void setZoom(float z) | Sets the zoom factor, clamped to 1..5, keeping the middle of the view in place. |
public int getPage() | The page at the middle of the view, zero based. |
public void setPage(int index) | Scrolls so that page index (zero based) is at the top of the view. |
public Image renderPage(int index, double scale) | Renders page index (zero based) to an image at scale pixels per point, white background, annotations included. |
public boolean isScrollableY() | Indicates whether the component should/could scroll on the Y axis |
public boolean isScrollableX() | Indicates whether the component should/could scroll on the X axis |
protected Dimension calcPreferredSize() | Calculates the preferred size based on component content. |
protected void laidOut() | This is a callback method to inform the Component when it’s been laidout on the parent Container |
public void paint(Graphics g) | This 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 boolean pinch(float scale) | Invoked by subclasses interested in handling pinch to zoom events, if true is returned other drag events will not be broadcast |
protected void pinchReleased(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). |
public void pointerReleased(int x, int y) | If this Component is focused, the pointer released event will call this method |
protected void deinitialize() | Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. |
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
Inherited methods
From Component
setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, initLaf, getUIManager, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, clearClientProperties, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, fireClicked, isSelectableInteraction, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, getBottomGap, getSideGap, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, setShouldCalcPreferredSize, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyPressed, keyReleased, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, dragInitiated, drawDraggedImage, draggingOver, dragEnter, dragExit, drop, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerPressed, pointerReleased, longPointerPress, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, getContextMenuCommands, setContextMenuCommands, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, getHoverStyle, setHoverStyle, isHovered, setHovered, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, paramString, refreshTheme, refreshTheme, refreshTheme, isDragActivated, getGridPosY, getGridPosX, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, setCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, isEnabled, setEnabled, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, cancelRepaints, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip
Constructor details
PdfViewer
public PdfViewer(byte[] data)
throws IOExceptiondata.Throws
IOException- when the data is not a PDF, or it is encrypted with a user password.
PdfViewer
public PdfViewer(byte[] data, String password)
throws IOExceptiondata, opened with password (the user or
the owner password) when it is encrypted.Throws
IOException- when the data is not a PDF or the password is wrong.
Method details
open
public static PdfViewer open(InputStream in)
throws IOExceptionin, which is closed.Throws
IOException- when reading fails or the data is not a PDF.
getPageCount
public int getPageCount()getZoom
public float getZoom()setZoom
public void setZoom(float z)getPage
public int getPage()setPage
public void setPage(int index)index (zero based) is at the top of the view.renderPage
public Image renderPage(int index, double scale)index (zero based) to an image at scale pixels per
point, white background, annotations included. Usable without
showing the viewer, for a thumbnail or a share sheet.isScrollableY
public boolean isScrollableY()Returns
isScrollableX
public boolean isScrollableX()Returns
calcPreferredSize
protected Dimension calcPreferredSize()Returns
laidOut
protected void laidOut()paint
public void paint(Graphics g)Parameters
gGraphics- the component graphics
pinch
protected boolean pinch(float scale)Parameters
scalefloat- 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
pinchReleased
protected void pinchReleased(int x, int y)Parameters
xint- The x-coordinate of the remaining finger in the drag. (Absolute)
yint- The y-coordinate of the remaining finger in the drag. (Absolute)
pointerReleased
public void pointerReleased(int x, int y)Parameters
xint- the pointer x coordinate
yint- the pointer y coordinate
deinitialize
protected void deinitialize()