DEV Community


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.

Enter fullscreen mode Exit fullscreen mode

2# The relevant code snippet

import com.spire.pdf.*;
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(, 3f);
        PdfPen pen1 = new PdfPen(new PdfRGBColor(, 1f);

        //Set dash style and pattern
        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
Enter fullscreen mode Exit fullscreen mode

3# A screenshot of the generated PDF document

Top comments (0)