DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • JavaScript Frameworks: The Past, the Present, and the Future
  • Essential Security Measures for PDF Documents
  • Building a PDF Viewer From Scratch
  • Template-Based PDF Document Generation in JavaScript

Trending

  • No More Cheap Claude: 4 First Principles of Token Economics in 2026
  • A Walk-Through of the DZone Article Editor
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • Offline-First Patch Management for 10,000 Edge Nodes: A Practical Architecture That Scales
  1. DZone
  2. Coding
  3. JavaScript
  4. Navigation From Adobe Reader With Konva.js

Navigation From Adobe Reader With Konva.js

In one of the popular PDF viewers, "Acrobat Reader", there is a tool called the "Hand Tool." We will implement similar behavior using the Konva.js library.

By 
Marat Minulin user avatar
Marat Minulin
·
Aug. 13, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

In one of the popular PDF viewers, Acrobat Reader, there is a tool called the "Hand Tool." It allows you to navigate through the document by dragging and dropping while holding down the mouse button. You can activate the "Hand Tool" by clicking the corresponding button on the toolbar.

“Hand Tool” button in Acrobat Reader

“Hand Tool” button in Acrobat Reader

In this article, we will implement similar behavior using the Konva.js library.

Tutorial

First off, we need to implement the ability to view document pages. To achieve this, we will define a list of pages using the following array:

JavaScript
 
const pages = [
  { pageId: 1, width: 2016, height: 2264, imageURL, offsetY: 0 },
  { pageId: 2, width: 2016, height: 2264, imageURL, offsetY: 2264 },
  { pageId: 3, width: 2016, height: 2264, imageURL, offsetY: 4528 }
];


Here, for each page, the page image URL imageURL and the offset from the beginning of the document offsetY are specified. Then, we will implement a component responsible for displaying the page:

JavaScript
 
import { Image } from "react-konva";
import useImage from "use-image";

export default function Page({ width, height, imageURL, offsetY }) {
  const [image] = useImage(imageURL);

  if (!image) {
    return null;
  }

  return (
    <Image
      x={0}
      y={0}
      image={image}
      width={width}
      height={height}
      offsetY={-offsetY}
    />
  );
}


To load an image by URL, the useImage hook is used. Then, the loaded image is passed to the Image component from the Konva.js library for display.

When working with the "Hand Tool" tool, the position of the document changes, and accordingly, the position of the scroll changes. Therefore, the next step is to implement the ability to scroll the document. For this, we will use a solution specified in the official documentation of the library and adapt it to our React application:

JavaScript
 
export default function App() {
  const [scroll, setScroll] = useState({ left: 0, top: 0 });

  const handleScroll = useCallback((event) => {
    const { scrollLeft, scrollTop } = event.currentTarget;

    setScroll({ left: scrollLeft, top: scrollTop });
  }, []);

  const stageStyles = useMemo(() => {
    return { transform: `translate(${scroll.left}px, ${scroll.top}px)` };
  }, [scroll]);

  return (
    <div className="Scroll" onScroll={handleScroll}>
      <div className="Content">
        <Stage
          x={-scroll.left}
          y={-scroll.top}
          width={window.innerWidth}
          height={window.innerHeight}
          style={stageStyles}
        >
          <Layer>
            {pages.map((page, index) => (
              <Page
                key={index}
                width={page.width}
                height={page.height}
                imageURL={page.imageURL}
                offsetY={-page.offsetY}
              />
            ))}
          </Layer>
        </Stage>
      </div>
    </div>
  );
}


The main idea is that when scrolling, the position of the Stage changes, and at the same time, the position of the parent element that wraps the Stage changes.

The last step is to implement the "Hand Tool" tool, but first, let's figure out how it works: this will help us understand how to implement it. When the tool is active, it allows the user to hold down the document with the mouse button, as in Drag and Drop, and move around the document by dragging it, i.e., changing its position, specified by the point with coordinates X and Y.

From here, it follows that we need to handle the drag-and-drop event and change the position of the document. The Konva.js library provides corresponding handlers for the drag-and-drop event, but we will use the dragBoundFunc function. This function is used to override the position during the drag-and-drop event. Overriding the position is necessary for additional validation to prevent the scene position from being moved beyond the document boundaries. 

Let's move on to the implementation, and then we'll discuss it:

JavaScript
 
export default function App() {
  const rootRef = useRef(null);
  const [isHandToolOn, setHandToolStatus] = useState(false);
  const [scroll, setScroll] = useState({ left: 0, top: 0 });

  const handleClick = useCallback(() => {
    setHandToolStatus((prev) => !prev);
  }, []);

  const handleScroll = useCallback((event) => {
    const { scrollLeft, scrollTop } = event.currentTarget;

    setScroll({ left: scrollLeft, top: scrollTop });
  }, []);

  const stageStyles = useMemo(() => {
    return { transform: `translate(${scroll.left}px, ${scroll.top}px)` };
  }, [scroll]);

  const scrollTo = useCallback(({ left, top }) => {
    rootRef.current.scrollLeft = left;
    rootRef.current.scrollTop = top;

    setScroll({ left, top });
  }, []);

  const handleDrag = useCallback(
    (dragPosition) => {
      const {
        scrollHeight,
        scrollWidth,
        clientHeight: rootHeight,
        clientWidth: rootWidth
      } = rootRef.current;

      const scrollableWidth = Math.max(0, scrollWidth - rootWidth);
      const scrollableHeight = Math.max(0, scrollHeight - rootHeight);

      const leftMin = Math.max(0, -dragPosition.x);
      const topMin = Math.max(0, -dragPosition.y);

      const left = Math.min(leftMin, scrollableWidth);
      const top = Math.min(topMin, scrollableHeight);

      scrollTo({ left, top });

      return { x: -left, y: -top };
    },
    [scrollTo]
  );

  return (
    <div className="App">
      <button type="button" onClick={handleClick}>
        Hand Toll: {isHandToolOn ? "On" : "Off"}
      </button>
      <div ref={rootRef} className="Scroll" onScroll={handleScroll}>
        <div className="Content">
          <Stage
            draggable={isHandToolOn}
            x={-scroll.left}
            y={-scroll.top}
            width={window.innerWidth}
            height={window.innerHeight}
            style={stageStyles}
            dragBoundFunc={handleDrag}
          >
            <Layer>
              {pages.map((page, index) => (
                <Page
                  key={index}
                  width={page.width}
                  height={page.height}
                  imageURL={page.imageURL}
                  offsetY={-page.offsetY}
                />
              ))}
            </Layer>
          </Stage>
        </div>
      </div>
    </div>
  );
}


We have added a "Hand Tool: On/Off" button to the page, which can be used to activate the "Hand Tool." If the "Hand Tool" is active, the scene can also be moved using behavior similar to the drag and drop event. Then we added the corresponding handleDrag handler, in which we checked that the position of the Stage does not go beyond the document boundaries and update the position of the document and the scrollbar. The "Hand Tool" tool is ready, and now the document can be moved not only using the scrollbar but also by dragging the document pages with the mouse. You can find the full source code and example on CodeSandbox.

Closing Thought

I hope that you found this article useful and interesting. In the next article, we will continue to implement various functionality using the Konva.js library.

Document JavaScript Library PDF Tool

Published at DZone with permission of Marat Minulin. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • JavaScript Frameworks: The Past, the Present, and the Future
  • Essential Security Measures for PDF Documents
  • Building a PDF Viewer From Scratch
  • Template-Based PDF Document Generation in JavaScript

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook