Apache PDFBox is an open source pure-Java library that can be used to create, render, print, split, merge, alter, verify and extract text and meta-data of PDF files.
This example covers the following topics
- Create a PDF document
- Add document properties such as Author, Title, Creation Date, Page Size, etc.
- Add Label Text with various font size and style
- Add Paragraph Text
- Draw lines and rectangle to create design layouts
- Insert an Image such as Company Logo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | import java.awt.Color; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; public class GeneratePDF { static float MARGIN = 25 ; public static void main(String[] args) { try { // Creating PDF document object PDDocument document = new PDDocument(); // Set document properties setDocumentProperties(document); // Add a page to the document with proper size PDPage page = new PDPage(PDRectangle.LETTER); document.addPage(page); // Insert an Image insertImage(document, page, "images/apple_logo.png" , MARGIN , 780 ); // Add some Text addText(document, page, "My sample TEXT for PDF" , MARGIN , 650 ); // Add paragraph String data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ; addParagraph(document, page, data, 0 , 625 ); // Draw Line drawLines(document, page, 25 , 500 ); // Draw Rectangle drawRectangle(document, page, 25 , 450 ); // Saving the document document.save( "docs/out.pdf" ); // Closing the document document.close(); } catch (IOException e) { e.printStackTrace(); } } private static void setDocumentProperties(PDDocument document) { // Creating the PDDocumentInformation object PDDocumentInformation docInformation = document.getDocumentInformation(); // Setting the author of the document docInformation.setAuthor( "BetterThanZero" ); // Setting the title of the document docInformation.setTitle( "PDF Document" ); // Setting the creator of the document docInformation.setCreator( "mysamplecode.com" ); // Setting the subject of the document docInformation.setSubject( "Learn PDFBox" ); // Setting the created date of the document Calendar date = new GregorianCalendar(); date.set( 2019 , 04 , 28 ); docInformation.setCreationDate(date); docInformation.setModificationDate(date); // Setting keywords for the document docInformation.setKeywords( "samplecode, first pdf, pdfbox" ); } private static void insertImage(PDDocument document, PDPage page, String imageName, float x, float y) { try { // Get Content Stream for Writing Data PDPageContentStream contentStream = new PDPageContentStream(document, page); // Creating PDImageXObject object PDImageXObject pdImage = PDImageXObject.createFromFile(imageName , document); // Drawing the image in the PDF document contentStream.drawImage(pdImage, x, y- 100 , 100 , 100 ); // Closing the content stream contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } private static void addText(PDDocument document, PDPage page, String myText, float x, float y) { try { // Get Content Stream for Writing Data PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true ); // Begin the Content stream contentStream.beginText(); // Setting the font to the Content stream contentStream.setFont(PDType1Font.TIMES_ROMAN, 12 ); // Setting the position for the line contentStream.newLineAtOffset(x, y); // Adding text in the form of string contentStream.showText(myText); // Ending the content stream contentStream.endText(); // Closing the content stream contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } private static void addParagraph(PDDocument document, PDPage page, String myText, float x, float y) { try { // Setting the font PDFont pdfFont = PDType1Font.TIMES_ROMAN; float fontSize = 12 ; float leading = 1 .5f * fontSize; // Get the Width and X/Y coordinates PDRectangle mediabox = page.getMediaBox(); float margin = MARGIN; float width = mediabox.getWidth() - ( 2 * margin); float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; if (x > 0 ){ width = width - x; startX = startX + x; } if (y > 0 ){ startY = y; } // Split the paragraph based on width and font size into multiple lines ArrayList<string> lines = new ArrayList<string>(); int lastSpace = - 1 ; while (myText.length() > 0 ) { int spaceIndex = myText.indexOf( ' ' , lastSpace + 1 ); if (spaceIndex < 0 ) spaceIndex = myText.length(); String subString = myText.substring( 0 , spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000 ; if (size > width) { if (lastSpace < 0 ) lastSpace = spaceIndex; subString = myText.substring( 0 , lastSpace); lines.add(subString); myText = myText.substring(lastSpace).trim(); lastSpace = - 1 ; } else if (spaceIndex == myText.length()) { lines.add(myText); myText = "" ; } else { lastSpace = spaceIndex; } } // Get Content Stream for Writing Data PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true ); contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.setNonStrokingColor(Color.RED); contentStream.newLineAtOffset(startX, startY); for (String line: lines) { contentStream.showText(line); contentStream.newLineAtOffset( 0 , -leading); } contentStream.endText(); contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } private static void drawLines(PDDocument document, PDPage page, float x, float y) { try { PDRectangle mediabox = page.getMediaBox(); float margin = MARGIN; float width = mediabox.getWidth() - ( 2 * margin); // Get Content Stream for Writing Data PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true ); // Setting the non stroking color contentStream.setStrokingColor(Color.GREEN); // lets make some lines contentStream.moveTo(x, y); contentStream.lineTo(x + width, y); contentStream.lineTo(x + width, y + 25 ); contentStream.lineTo(x, y + 25 ); contentStream.stroke(); contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } private static void drawRectangle(PDDocument document, PDPage page, float x, float y) { try { PDRectangle mediabox = page.getMediaBox(); float margin = MARGIN; float width = mediabox.getWidth() - ( 2 * margin); // Get Content Stream for Writing Data PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true ); // Setting the non stroking color contentStream.setNonStrokingColor(Color.LIGHT_GRAY); // Drawing a rectangle contentStream.addRect(x, y, width, 25 ); // Drawing a rectangle contentStream.fill(); contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } } </string></string> |
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.