github.com/unidoc/unidoc@v2.2.0+incompatible/pdf/creator/line.go (about) 1 /* 2 * This file is subject to the terms and conditions defined in 3 * file 'LICENSE.md', which is part of this source code package. 4 */ 5 6 package creator 7 8 import ( 9 "math" 10 11 "github.com/unidoc/unidoc/pdf/contentstream/draw" 12 "github.com/unidoc/unidoc/pdf/model" 13 ) 14 15 // Line defines a line between point 1 (X1,Y1) and point 2 (X2,Y2). The line ending styles can be none (regular line), 16 // or arrows at either end. The line also has a specified width, color and opacity. 17 // Implements the Drawable interface and can be drawn on PDF using the Creator. 18 type Line struct { 19 x1 float64 20 y1 float64 21 x2 float64 22 y2 float64 23 lineColor *model.PdfColorDeviceRGB 24 lineWidth float64 25 } 26 27 // NewLine creates a new Line with default parameters between (x1,y1) to (x2,y2). 28 func NewLine(x1, y1, x2, y2 float64) *Line { 29 l := &Line{} 30 31 l.x1 = x1 32 l.y1 = y1 33 l.x2 = x2 34 l.y2 = y2 35 36 l.lineColor = model.NewPdfColorDeviceRGB(0, 0, 0) 37 l.lineWidth = 1.0 38 39 return l 40 } 41 42 // GetCoords returns the (x1, y1), (x2, y2) points defining the Line. 43 func (l *Line) GetCoords() (float64, float64, float64, float64) { 44 return l.x1, l.y1, l.x2, l.y2 45 } 46 47 // SetLineWidth sets the line width. 48 func (l *Line) SetLineWidth(lw float64) { 49 l.lineWidth = lw 50 } 51 52 // SetColor sets the line color. 53 // Use ColorRGBFromHex, ColorRGBFrom8bit or ColorRGBFromArithmetic to make the color object. 54 func (l *Line) SetColor(col Color) { 55 l.lineColor = model.NewPdfColorDeviceRGB(col.ToRGB()) 56 } 57 58 // Length calculates and returns the line length. 59 func (l *Line) Length() float64 { 60 return math.Sqrt(math.Pow(l.x2-l.x1, 2.0) + math.Pow(l.y2-l.y1, 2.0)) 61 } 62 63 // GeneratePageBlocks draws the line on a new block representing the page. Implements the Drawable interface. 64 func (l *Line) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { 65 block := NewBlock(ctx.PageWidth, ctx.PageHeight) 66 67 drawline := draw.Line{ 68 LineWidth: l.lineWidth, 69 Opacity: 1.0, 70 LineColor: l.lineColor, 71 LineEndingStyle1: draw.LineEndingStyleNone, 72 LineEndingStyle2: draw.LineEndingStyleNone, 73 X1: l.x1, 74 Y1: ctx.PageHeight - l.y1, 75 X2: l.x2, 76 Y2: ctx.PageHeight - l.y2, 77 } 78 79 contents, _, err := drawline.Draw("") 80 if err != nil { 81 return nil, ctx, err 82 } 83 84 err = block.addContentsByString(string(contents)) 85 if err != nil { 86 return nil, ctx, err 87 } 88 89 return []*Block{block}, ctx, nil 90 }