You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Eclipse IDE下PDF批注Windows应用开发:PDF显示与批注实现问询

Java Swing PDF Viewer & Annotation in Eclipse: A Step-by-Step Guide

Hey there! Let me walk you through how to build your windowed PDF annotation app in Eclipse—this is totally doable with some great open-source Java libraries, no need to reinvent the wheel.

First: Displaying PDFs in a Java Window

Java doesn’t have native PDF rendering, so you’ll need a library. Here are the most reliable options, with quick implementation examples for Eclipse:

1. Apache PDFBox (Free, Open-Source)

This is my go-to for PDF tasks. To get started:

  • Add PDFBox to your Eclipse project:

    • If using Maven, add this dependency to your pom.xml:
      <dependency>
          <groupId>org.apache.pdfbox</groupId>
          <artifactId>pdfbox</artifactId>
          <version>2.0.32</version> <!-- Use the latest stable version -->
      </dependency>
      
    • If not using Maven, download the PDFBox JARs, drop them into a lib folder in your project, then right-click > Build Path > Add to Build Path.
  • Basic Swing Viewer Code:
    This renders a PDF page into a Swing component you can add to your window:

    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.rendering.PDFRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    
    public class PDFViewer extends JFrame {
        public PDFViewer(String pdfPath) {
            super("PDF Viewer");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
    
            try (PDDocument document = PDDocument.load(new File(pdfPath))) {
                PDFRenderer renderer = new PDFRenderer(document);
                // Render the first page (index 0)
                Image image = renderer.renderImage(0);
                JLabel label = new JLabel(new ImageIcon(image));
                JScrollPane scrollPane = new JScrollPane(label);
                add(scrollPane, BorderLayout.CENTER);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "Failed to load PDF");
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> new PDFViewer("path/to/your/file.pdf").setVisible(true));
        }
    }
    

2. ICEpdf (Another Solid Option)

ICEpdf has a built-in Swing viewer component that handles page navigation automatically, saving you code. Just add the ICEpdf JARs to your project, then use:

import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import javax.swing.*;
import java.awt.*;

public class ICEpdfViewer extends JFrame {
    public ICEpdfViewer(String pdfPath) {
        super("ICEpdf Viewer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);

        SwingController controller = new SwingController();
        SwingViewBuilder factory = new SwingViewBuilder(controller);
        JPanel viewerComponentPanel = factory.buildViewerPanel();
        
        // Add navigation bar
        add(factory.buildToolBar(), BorderLayout.NORTH);
        add(viewerComponentPanel, BorderLayout.CENTER);

        controller.openDocument(pdfPath);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ICEpdfViewer("path/to/your/file.pdf").setVisible(true));
    }
}

Second: Adding Annotations & Underlines

Once you can display the PDF, adding annotations (like text notes or underlines) is straightforward with the same libraries. Let’s use PDFBox for this example:

Adding a Text Annotation

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationText;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import java.io.File;

public class AddTextAnnotation {
    public static void main(String[] args) {
        try (PDDocument document = PDDocument.load(new File("input.pdf"))) {
            PDPage page = document.getPage(0); // Get first page

            // Create text annotation
            PDAnnotationText textAnnotation = new PDAnnotationText();
            textAnnotation.setContents("This is my annotation!");
            textAnnotation.setTitle("Arisha's Note");
            // Set position (x, y, width, height) - coordinates are from bottom-left of the page
            textAnnotation.setRectangle(new PDRectangle(100, 500, 200, 50));
            textAnnotation.setOpen(true); // Show annotation by default

            page.getAnnotations().add(textAnnotation);
            document.save("output_with_annotation.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Adding an Underline

Use PDAnnotationTextMarkup for text markup like underlines:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import java.io.File;

public class AddUnderline {
    public static void main(String[] args) {
        try (PDDocument document = PDDocument.load(new File("input.pdf"))) {
            PDPage page = document.getPage(0);

            // Create underline annotation
            PDAnnotationTextMarkup underline = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_UNDERLINE);
            // Set the rectangle around the text you want to underline
            underline.setRectangle(new PDRectangle(100, 450, 300, 10));
            // Set quad points (defines the area of the underline - adjust based on your text position)
            float[] quadPoints = new float[] {100, 460, 400, 460, 100, 450, 400, 450};
            underline.setQuadPoints(quadPoints);
            underline.setContents("Important text!"); // Optional note for the underline

            page.getAnnotations().add(underline);
            document.save("output_with_underline.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tying It to Your Window App

To let users interactively add annotations (e.g., click to place an underline), add mouse listeners to your PDF display component. Track mouse clicks/drags to get coordinates, then create the annotation using those coordinates and save the modified PDF.


Final Tips for Eclipse

  • Debugging: Use Eclipse’s debug mode to step through annotation code—this helps with coordinate positioning (remember PDF coordinates start at the bottom-left!).
  • Library Versions: Always use the latest stable versions of PDFBox/ICEpdf to avoid bugs.
  • Performance: For large PDFs, render pages on demand instead of all at once to keep your app responsive.

内容的提问来源于stack exchange,提问作者Arisha Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:58:20