DEV Community

lu liu
lu liu

Posted on

Mastering PDF Graphics: Drawing Shapes in Java with Spire.PDF

In the realm of Java application development, the ability to generate dynamic and visually rich PDF documents is a common and often critical requirement. From custom reports and invoices to interactive forms, PDFs serve as a universal standard for document exchange. However, manipulating PDF content programmatically can be a complex endeavor, often requiring specialized libraries to abstract away the intricate details of the PDF specification. This is where Spire.PDF for Java comes into play as an effective and powerful solution. It simplifies the process of creating, reading, and editing PDF documents, including the fundamental task of drawing various shapes. This tutorial will provide clear, step-by-step guidance on how to leverage Spire.PDF for Java to draw lines, arcs, rectangles, ellipses, and more, empowering you to craft sophisticated PDF graphics with ease.


Getting Started: Integrating Spire.PDF for Java

Spire.PDF for Java is a professional PDF API designed to enable developers to perform a wide range of PDF manipulation tasks directly within their Java applications. It offers extensive functionalities, from text extraction and form filling to advanced graphics and security features.

To begin using Spire.PDF for Java, you need to add its dependency to your Java project. If you're using Maven, you can include the following in your pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.1.4</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Precision Lines: Drawing Straight Segments

Drawing lines is one of the most basic yet crucial graphic operations. In Spire.PDF, you define a line by its starting and ending coordinates. You can also customize its appearance using PdfPen, which allows you to set the line's color and width.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class drawLine {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        // Add a Page
        PdfPageBase page = pdf.getPages().add();

        // Save the current graphics state
        PdfGraphicsState state = page.getCanvas().save();

        // Specify the starting X and y coordinates of the line
        float x = 100;
        float y = 70;

        // Specify the length of the line
        float width = 300;

        // Create a PDF pen with blue color and thickness of 2
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.BLUE), 2f);

        // Draw a solid line on the page using the pen
        page.getCanvas().drawLine(pen, x, y, x + width, y);

        // Set the pen style to dashed
        pen.setDashStyle(PdfDashStyle.Dash);

        // Set the dashed line pattern
        pen.setDashPattern(new float[]{1, 4, 1});

        // Draw a dashed line on the page using the pen
        page.getCanvas().drawLine(pen, x, y+30, x + width, y+30);

        // Restore the previous saved graphics state
        page.getCanvas().restore(state);

        // Save the PDF document
        pdf.saveToFile("DrawLines.pdf");

        // Close the document and release resources
        pdf.close();
        pdf.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

This code snippet demonstrates drawing three distinct lines, showcasing how to vary their properties.


Curving Paths: Arcs and Pie Charts

Curved shapes add visual interest and are vital for data representation. Spire.PDF provides methods for drawing arcs and pie segments.

An arc is a segment of an ellipse defined by a bounding rectangle, a start angle, and a sweep angle. Pie segments are essentially arcs that are "closed" to the center point of their ellipse, often used for pie charts. You can fill these segments using PdfBrush.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class drawArcAndPie {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        // Add a Page
        PdfPageBase page = pdf.getPages().add();

        // Save the current graphics state
        PdfGraphicsState state = page.getCanvas().save();

        // Create a PDF pen with specified color and thickness of 2
        PdfPen pen = new PdfPen(new PdfRGBColor(new Color(139,0,0)), 2f);

        // Specify the start and sweep angles of the arc
        float startAngle = 90;
        float sweepAngle = 230;
        // Draw an arc on the page using the pen
        Rectangle2D.Float rect= new Rectangle2D.Float(30, 60, 120, 120);
        page.getCanvas().drawArc(pen, rect, startAngle, sweepAngle);

        // Specify the start and sweep angles of the pie chart
        float startAngle1 = 0;
        float sweepAngle1 = 330;
        // Draw a pie chart on the page using the pen
        Rectangle2D.Float rect2= new Rectangle2D.Float(200, 60, 120, 120);
        page.getCanvas().drawPie(pen, rect2, startAngle1, sweepAngle1);

        // Restore the previous saved graphics state
        page.getCanvas().restore(state);

        // Save the PDF document
        pdf.saveToFile("DrawArcAndPie.pdf");

        // Close the document and release resources
        pdf.close();
        pdf.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Structured Forms: Rectangles and Squares

Rectangles are fundamental shapes, used for everything from borders to backgrounds. Spire.PDF allows you to draw both outlined and filled rectangles. A square is simply a rectangle with equal width and height.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class drawRectangles {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        // Add a Page
        PdfPageBase page = pdf.getPages().add();

        // Save the current graphics state
        PdfGraphicsState state = page.getCanvas().save();

        // Create a PDF pen with specified color and thickness of 1.5
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.magenta), 1.5f);

        // Draw a rectangle on the page using the pen
        page.getCanvas().drawRectangle(pen, new Rectangle(20, 60, 150, 90));

        // Create a linear gradient brush
        Rectangle2D.Float rect = new Rectangle2D.Float(220, 60, 150, 90);
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect,new PdfRGBColor(Color.white),new PdfRGBColor(Color.blue),PdfLinearGradientMode.Vertical);

        // Create a new PDF pen with specified color and thickness of 0.5
        PdfPen pen1 = new PdfPen(new PdfRGBColor(Color.black), 0.5f);

        // Draw a filled rectangle using the new pen and linear gradient brush
        page.getCanvas().drawRectangle(pen1, linearGradientBrush, rect);

        // Restore the previous graphics state
        page.getCanvas().restore(state);

        // Save the PDF document
        pdf.saveToFile("DrawRectangles.pdf");

        // Close the document and release resources
        pdf.close();
        pdf.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Smooth Contours: Drawing Ellipses

Ellipses and circles provide smooth, curved forms. An ellipse is drawn within a specified bounding rectangle.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class drawEllipses {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        // Add a Page
        PdfPageBase page = pdf.getPages().add();

        // Save the current graphics state
        PdfGraphicsState state = page.getCanvas().save();

        // Create a PDF pen with specified color and thickness
        PdfPen pen = new PdfPen(new PdfRGBColor(new Color(95, 158, 160)), 1f);
        // Draw an ellipse on the page using the pen
        page.getCanvas().drawEllipse(pen, 30, 60, 150, 100);

        // Create a brush with specified color for filling
        PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(new Color(95, 158, 160)));
        // Draw a filled ellipse using the brush
        page.getCanvas().drawEllipse(brush, 220, 60, 150, 100);

        // Restore the previous graphics state
        page.getCanvas().restore(state);

        // Save the PDF document
        pdf.saveToFile("DrawEllipses.pdf");

        // Close the document and release resources
        pdf.close();
        pdf.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we've explored the fundamental techniques for drawing various shapes in PDF documents using Spire.PDF for Java. We covered setting up your environment, creating a basic PDF document, and then diving into the specifics of drawing lines, arcs, pie segments, rectangles, and ellipses. Spire.PDF's intuitive API simplifies what would otherwise be a complex task, providing developers with a robust toolset for creating rich and dynamic PDF graphics. By mastering these basic shape-drawing capabilities, you can build a strong foundation for more advanced PDF manipulation. We encourage you to experiment with different colors, line styles, and combinations of shapes to unleash the full potential of programmatic PDF creation in your Java development projects. The power to generate visually compelling and data-rich PDFs is now at your fingertips, ready to be integrated into your applications.

Top comments (0)