|
| 1 | +package org.fugerit.java.code.samples.pdfbox2; |
| 2 | + |
| 3 | +import org.apache.pdfbox.pdmodel.PDDocument; |
| 4 | +import org.apache.pdfbox.pdmodel.PDPage; |
| 5 | +import org.apache.pdfbox.pdmodel.PDPageContentStream; |
| 6 | +import org.apache.pdfbox.pdmodel.font.PDFont; |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.OutputStream; |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.List; |
| 11 | + |
| 12 | +/** |
| 13 | + * Line wrapping test. |
| 14 | + * |
| 15 | + * This code will wrap text on more lines if it is longer than maximum page width. |
| 16 | + */ |
| 17 | +public class LineWrapping { |
| 18 | + |
| 19 | + private void handleLine( String l, List<String> list, int maxSize ) { |
| 20 | + String[] splits = l.split( " " ); |
| 21 | + StringBuilder builder = new StringBuilder(); |
| 22 | + for ( int i=0; i<splits.length; i++ ) { |
| 23 | + String s = splits[i]; |
| 24 | + if ( builder.length() + s.length() > maxSize ) { |
| 25 | + list.add( builder.toString() ); |
| 26 | + builder = new StringBuilder(); |
| 27 | + } |
| 28 | + builder.append( s ); |
| 29 | + if ( i != splits.length - 1 ) { |
| 30 | + builder.append( " " ); |
| 31 | + } |
| 32 | + } |
| 33 | + list.add( builder.toString() ); |
| 34 | + } |
| 35 | + |
| 36 | + private List<String> splitLines( String[] lines, int maxSize ) { |
| 37 | + List<String> list = new ArrayList<>(); |
| 38 | + for ( String l : lines ) { |
| 39 | + if ( l.length() > maxSize ) { |
| 40 | + this.handleLine( l, list, maxSize ); |
| 41 | + } else { |
| 42 | + list.add( l ); |
| 43 | + } |
| 44 | + } |
| 45 | + return list; |
| 46 | + } |
| 47 | + |
| 48 | + public void generatePDF(OutputStream os, PDFont font, String[] lines) throws IOException { |
| 49 | + try (PDDocument document = new PDDocument()) { |
| 50 | + PDPage currentPage = new PDPage(); |
| 51 | + PDPageContentStream cs = new PDPageContentStream( document, currentPage ); |
| 52 | + float fontSize = 14; |
| 53 | + float leading = 12; |
| 54 | + cs.setFont( font, fontSize ); |
| 55 | + cs.setLeading( leading ); |
| 56 | + float baseX = 25; |
| 57 | + float baseY = 750; |
| 58 | + float offsetY = 0; |
| 59 | + float maxPageWidth = 1400; |
| 60 | + int maxLineLength = (int)(maxPageWidth/fontSize); // actual formula can be different depending on font |
| 61 | + List<String> list = splitLines( lines, maxLineLength ); |
| 62 | + for ( String s : list ) { |
| 63 | + cs.beginText(); |
| 64 | + cs.newLineAtOffset( baseX, baseY+offsetY ); |
| 65 | + cs.showText( s ); |
| 66 | + cs.endText(); |
| 67 | + offsetY-= fontSize; |
| 68 | + } |
| 69 | + cs.stroke(); |
| 70 | + cs.close(); |
| 71 | + document.addPage( currentPage ); |
| 72 | + document.save( os ); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments