如何在PDFBox中绘制三角形

时间:2015-09-18 10:31:51

标签: java pdf graphics pdfbox shapes

我试图通过在顶点(100,100),(110,100)和(110,110)之间绘制3条线来绘制三角形,使用PDFBox填充和描边路径。

使用的方法如下:

public void drawTriangle(PDPageContentStream pDPageContentStream) throws IOException {
    pDPageContentStream.appendRawCommands("q\n");
    pDPageContentStream.addLine(100, 100, 110, 100);
    pDPageContentStream.addLine(110, 100, 110, 110);
    pDPageContentStream.addLine(110, 110, 100, 100);
    pDPageContentStream.appendRawCommands("\nB*\n");
    pDPageContentStream.appendRawCommands("\nQ\n");
}

但是显示了 nonagon

请帮我画三角形!

1 个答案:

答案 0 :(得分:1)

以下程序在pdf文档上绘制三角形:

package pdf;

import java.awt.Color;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;


public class GeneratePdfDocument {

    public void GeneratePdfDocument() throws IOException, COSVisitorException {
        String shapePdfFilePath = "resources/triangle.pdf";

        PDDocument pDDocument = new PDDocument();
        PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
        pDDocument.addPage(page1);
        PDPageContentStream pDPageContentStream = new PDPageContentStream(pDDocument, page1);
        drawTriangle(pDPageContentStream, 300, 600, 250, 250);
        pDPageContentStream.close();
        pDDocument.save(shapePdfFilePath);
        pDDocument.close();
    }

    public void drawTriangle(PDPageContentStream pDPageContentStream, float x, float y, float width, float height) throws IOException {
        pDPageContentStream.appendRawCommands("q\n");
//        pDPageContentStream.setLineCapStyle(0);
        pDPageContentStream.setLineCapStyle(1);
        pDPageContentStream.setStrokingColor(Color.BLACK);
        pDPageContentStream.moveTo(x, y);
        pDPageContentStream.addLine(x, y, x + width, y);
        pDPageContentStream.addLine(x + width, y, x + width, y + width);
        pDPageContentStream.addLine(x + width, y + width, x, y);
        pDPageContentStream.appendRawCommands("B*\n");
        pDPageContentStream.appendRawCommands("Q\n");
    }

    public static void main(String[] agrgs) throws IOException, COSVisitorException {
        GeneratePdfDocument generatePdfDocument = new GeneratePdfDocument();
        generatePdfDocument.drawTriangle();
    }
}

(ps:由于三角形的尺寸太小而且线端帽样式设置为默认值(0),因此无法正确识别三角形!)