DEV Community

CodeSharing
CodeSharing

Posted on

Draw Dash and Solid Line to PDF using Java

In daily work, we may need to draw lines to a PDF document so that the text content inside it can be easily divided into several different parts. Beyond that, drawing lines can also serve the purpose of decoration. This article will show you how to draw dash and solid line using a free Java API.

1# Import the jar dependency of the free Java API (2 Method)
● Download the free API (Free Spire.PDF for Java) and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.

● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

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

2# The relevant code snippet

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

public class DrawLines {
    public static void main(String[] args) {

        //Create a new PdfDocument instance and add a new page
        PdfDocument pdf = new PdfDocument();
        PdfPageBase page = pdf.getPages().add();

        //Set location and size
        float x = 150;
        float y = 100;
        float width = 300;

        //Create pens
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.red), 3f);
        PdfPen pen1 = new PdfPen(new PdfRGBColor(Color.blue), 1f);

        //Set dash style and pattern
        pen.setDashStyle(PdfDashStyle.Dash);
        pen.setDashPattern(new float[]{1, 1, 1});

        //Draw lines to the PDF page
        page.getCanvas().drawLine(pen, x, y, x + width, y);
        page.getCanvas().drawLine(pen1, x, y+50, x + width, y+50);

        //Save the document
        pdf.saveToFile("output/drawLines.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

3# A screenshot of the generated PDF document
line

Top comments (0)