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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Measuring the Impact of AI on Software Engineering Productivity
  • Start Coding With Google Cloud Workstations
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  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.2K 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!