List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox
public PDRectangle getMediaBox()
From source file:jlotoprint.PrintViewUIPanelController.java
public PDDocument generatePDF() throws Exception { PDDocument doc = null;/*from w ww . j a va 2s . c o m*/ PDPage page = null; PDPageContentStream content = null; try { doc = new PDDocument(); List<Group> pageList = importPageList(Template.getSourceFile(), Template.getModel()); for (Parent node : pageList) { page = new PDPage(PDPage.PAGE_SIZE_A4); doc.addPage(page); PDRectangle mediaBox = page.getMediaBox(); float pageWidth = mediaBox.getWidth(); float pageHeight = mediaBox.getHeight(); node.setTranslateX(0); node.setTranslateY(0); node.setScaleX(1); node.setScaleY(1); node.applyCss(); node.layout(); HashMap<String, Double> result = resizeProportional(node.getBoundsInParent().getWidth(), node.getBoundsInParent().getHeight(), pageWidth, pageHeight, true); //get node image WritableImage nodeImage = node.snapshot(null, null); BufferedImage bufferedImage = SwingFXUtils.fromFXImage(nodeImage, null); //set page content content = new PDPageContentStream(doc, page); PDJpeg image = new PDJpeg(doc, bufferedImage, 1f); content.drawXObject(image, 0, 0, result.get("width").intValue(), result.get("height").intValue()); content.close(); } } catch (Exception ex) { throw ex; } finally { try { if (content != null) { content.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return doc; }
From source file:mil.tatrc.physiology.utilities.Excel2PDF.java
License:Apache License
public static void convert(String from, String to) throws IOException { FileInputStream xlFile = new FileInputStream(new File(from)); // Read workbook into HSSFWorkbook XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile); //We will create output PDF document objects at this point PDDocument pdf = new PDDocument(); //pdf.addTitle(); for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) { XSSFSheet xlSheet = xlWBook.getSheetAt(s); Log.info("Processing Sheet : " + xlSheet.getSheetName()); PDPage page = new PDPage(PDRectangle.A4); page.setRotation(90);/*from w ww .j av a2 s . c o m*/ pdf.addPage(page); PDRectangle pageSize = page.getMediaBox(); PDPageContentStream contents = new PDPageContentStream(pdf, page); contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference contents.setFont(PDType1Font.HELVETICA_BOLD, 16); contents.beginText(); contents.newLineAtOffset(50, pageSize.getWidth() - 50); contents.showText(xlSheet.getSheetName()); contents.endText(); contents.close(); int rows = xlSheet.getPhysicalNumberOfRows(); for (int r = 0; r < rows; r++) { XSSFRow row = xlSheet.getRow(r); if (row == null) continue; int cells = row.getPhysicalNumberOfCells(); if (cells == 0) continue;// Add an empty Roe } } /* //We will use the object below to dynamically add new data to the table PdfPCell table_cell; //Loop through rows. while(rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Fetch CELL switch(cell.getCellType()) { //Identify CELL type //you need to add more code here based on //your requirement / transformations case Cell.CELL_TYPE_STRING: //Push the data from Excel to PDF Cell table_cell=new PdfPCell(new Phrase(cell.getStringCellValue())); //feel free to move the code below to suit to your needs my_table.addCell(table_cell); break; } //next line } } */ pdf.save(new File(to)); pdf.close(); xlWBook.close(); xlFile.close(); //close xls }
From source file:net.timendum.pdf.Images2HTML.java
License:Open Source License
@Override protected void processOperator(PDFOperator operator, List arguments) throws IOException { String operation = operator.getOperation(); if (INVOKE_OPERATOR.equals(operation)) { COSName objectName = (COSName) arguments.get(0); Map<String, PDXObject> xobjects = getResources().getXObjects(); PDXObject xobject = xobjects.get(objectName.getName()); if (xobject instanceof PDXObjectImage) { PDXObjectImage image = (PDXObjectImage) xobject; PDPage page = getCurrentPage(); int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); double pageHeight = page.getMediaBox().getHeight(); Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix(); float yScaling = ctmNew.getYScale(); float angle = (float) Math.acos(ctmNew.getValue(0, 0) / ctmNew.getXScale()); if (ctmNew.getValue(0, 1) < 0 && ctmNew.getValue(1, 0) > 0) { angle = (-1) * angle;//from ww w . ja v a 2s . c om } ctmNew.setValue(2, 1, (float) (pageHeight - ctmNew.getYPosition() - Math.cos(angle) * yScaling)); ctmNew.setValue(2, 0, (float) (ctmNew.getXPosition() - Math.sin(angle) * yScaling)); // because of the moved 0,0-reference, we have to shear in the opposite direction ctmNew.setValue(0, 1, (-1) * ctmNew.getValue(0, 1)); ctmNew.setValue(1, 0, (-1) * ctmNew.getValue(1, 0)); AffineTransform ctmAT = ctmNew.createAffineTransform(); ctmAT.scale(1f / imageWidth, 1f / imageHeight); Image entry = new Image(); entry.x = ctmNew.getXPosition(); entry.image = image; entry.name = objectName.getName(); images.put(page, ctmNew.getYPosition(), entry); } else if (xobject instanceof PDXObjectForm) { // save the graphics state getGraphicsStack().push((PDGraphicsState) getGraphicsState().clone()); PDPage page = getCurrentPage(); PDXObjectForm form = (PDXObjectForm) xobject; COSStream invoke = (COSStream) form.getCOSObject(); PDResources pdResources = form.getResources(); if (pdResources == null) { pdResources = page.findResources(); } // if there is an optional form matrix, we have to // map the form space to the user space Matrix matrix = form.getMatrix(); if (matrix != null) { Matrix xobjectCTM = matrix.multiply(getGraphicsState().getCurrentTransformationMatrix()); getGraphicsState().setCurrentTransformationMatrix(xobjectCTM); } processSubStream(page, pdResources, invoke); // restore the graphics state setGraphicsState(getGraphicsStack().pop()); } } else { super.processOperator(operator, arguments); } }
From source file:openstitcher.core.PDFRenderer.java
License:Open Source License
public static void render(Design design, String location, ArrayList<LegendEntry> legend) throws IOException, COSVisitorException { PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page);/*from w w w. j av a 2 s .c om*/ PDFont font = PDType1Font.HELVETICA; PDPageContentStream contentStream = new PDPageContentStream(document, page); float pageWidth = page.getMediaBox().getWidth(); float pageHeight = page.getMediaBox().getHeight(); float sideMargin = 70.0f; float capsMargin = 30.0f; // draw the document title contentStream.beginText(); contentStream.setFont(font, 24.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - 24.0f); contentStream.drawString(design.title); contentStream.endText(); // draw the document author contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f)); contentStream.drawString(design.author); contentStream.endText(); // draw the document license contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f)); contentStream.drawString(design.license); contentStream.endText(); // draw the physical size contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(pageWidth - sideMargin - 100.0f, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f)); contentStream.drawString(design.physicalSize); contentStream.endText(); // draw the pattern float gridWidth = pageWidth - (sideMargin * 2); float widthPerCell = gridWidth / (float) design.pattern.getPatternWidth(); float gridStartX = sideMargin; float gridStopX = sideMargin + (widthPerCell * design.pattern.getPatternWidth()); float gridStartY = pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f); float gridStopY = (pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f)) - (widthPerCell * design.pattern.getPatternHeight()); // draw the pattern: background for (int i = 0; i < design.pattern.getPatternWidth(); i++) { for (int j = 0; j < design.pattern.getPatternHeight(); j++) { Yarn cellYarn = design.pattern.getPatternCell(i, j); if (cellYarn != null) { contentStream.setNonStrokingColor(cellYarn.color); contentStream.fillRect(gridStartX + (widthPerCell * i), gridStartY - (widthPerCell * j) - widthPerCell, widthPerCell, widthPerCell); } } } // draw the pattern: grid outline contentStream.setStrokingColor(Color.black); for (int i = 0; i < design.pattern.getPatternWidth() + 1; i++) { // draw vertical lines float xCoord = gridStartX + (widthPerCell * i); if (i % 5 == 0) { contentStream.setLineWidth(2.0f); } else { contentStream.setLineWidth(1.0f); } contentStream.drawLine(xCoord, gridStartY, xCoord, gridStopY); } for (int i = 0; i < design.pattern.getPatternHeight() + 1; i++) { // draw horizontal lines float yCoord = gridStartY - (widthPerCell * i); if (i % 5 == 0) { contentStream.setLineWidth(2.0f); } else { contentStream.setLineWidth(1.0f); } contentStream.drawLine(gridStartX, yCoord, gridStopX, yCoord); } // draw the pattern: characters contentStream.setNonStrokingColor(Color.black); float centeringOffset = widthPerCell / 5.0f; for (int i = 0; i < design.pattern.getPatternWidth(); i++) { for (int j = 0; j < design.pattern.getPatternHeight(); j++) { Yarn cellYarn = design.pattern.getPatternCell(i, j); if (cellYarn != null) { int index = LegendEntry.findIndexByYarn(legend, cellYarn); if (index == -1) { throw new RuntimeException("Cell did not exist in legend."); } contentStream.beginText(); contentStream.setFont(font, widthPerCell); contentStream.moveTextPositionByAmount(gridStartX + (widthPerCell * i) + centeringOffset, gridStartY - (widthPerCell * j) - widthPerCell + centeringOffset); contentStream.drawString(legend.get(index).character); contentStream.endText(); } } } // draw the legend float legendWidth = pageWidth - (sideMargin * 2); float widthPerLegendCell = legendWidth / (float) legend.size(); float legendStartX = sideMargin; float legendStopX = pageWidth - sideMargin; float legendStartY = capsMargin + 12.0f; float legendStopY = capsMargin; float legendCellPadding = 1.0f; float exampleCellWidth = 10.0f; for (int i = 0; i < legend.size(); i++) { // draw box contentStream.setNonStrokingColor(legend.get(i).yarn.color); contentStream.fillRect(legendStartX + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding, exampleCellWidth, exampleCellWidth); // draw character contentStream.beginText(); contentStream.setNonStrokingColor(legend.get(i).fontColor); contentStream.setFont(font, 10.0f); contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding); contentStream.drawString(legend.get(i).character); contentStream.endText(); // draw yarn name contentStream.beginText(); contentStream.setNonStrokingColor(Color.black); contentStream.setFont(font, 10.0f); contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + exampleCellWidth + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding); contentStream.drawString(legend.get(i).yarn.name); contentStream.endText(); } contentStream.close(); document.save(location); document.close(); }
From source file:org.apache.camel.component.pdf.text.DefaultWriteStrategy.java
License:Apache License
@Override public PDDocument write(Collection<String> lines, PDDocument document) throws IOException { PDPage page = new PDPage(pdfConfiguration.getPageSize()); document.addPage(page);/* ww w .ja v a 2 s . c o m*/ float x = pdfConfiguration.getMarginLeft(); float y = page.getMediaBox().getHeight() - pdfConfiguration.getMarginTop(); float averageFontHeight = PdfUtils.getAverageFontHeight(pdfConfiguration.getFont(), pdfConfiguration.getFontSize()); float lineSpacing = averageFontHeight * 2; PDPageContentStream contentStream = initializeContentStream(document, page); for (String line : lines) { writeLine(x, y, line, contentStream); y -= lineSpacing; if (goToNextPage(y)) { contentStream.close(); page = new PDPage(pdfConfiguration.getPageSize()); document.addPage(page); contentStream = initializeContentStream(document, page); y = page.getMediaBox().getHeight() - pdfConfiguration.getMarginTop(); } } contentStream.close(); return document; }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
/** * Creates a stream (from FOP's PDF library) from a PDF page parsed with PDFBox. * @param sourceDoc the source PDF the given page to be copied belongs to * @param page the page to transform into a stream * @param key value to use as key for the stream * @param atdoc adjustment for stream//from w w w.j a va 2s. c o m * @param fontinfo fonts * @param pos rectangle * @return the stream * @throws IOException if an I/O error occurs */ public String createStreamFromPDFBoxPage(PDDocument sourceDoc, PDPage page, String key, AffineTransform atdoc, FontInfo fontinfo, Rectangle pos) throws IOException { handleAnnotations(sourceDoc, page, atdoc); if (pageNumbers.containsKey(targetPage.getPageIndex())) { pageNumbers.get(targetPage.getPageIndex()).set(0, targetPage.makeReference()); } PDResources sourcePageResources = page.getResources(); PDStream pdStream = getContents(page); COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT); COSDictionary fontsBackup = null; UniqueName uniqueName = new UniqueName(key, sourcePageResources); String newStream = null; if (fonts != null && pdfDoc.isMergeFontsEnabled()) { fontsBackup = new COSDictionary(fonts); MergeFontsPDFWriter m = new MergeFontsPDFWriter(fonts, fontinfo, uniqueName, parentFonts, currentMCID); newStream = m.writeText(pdStream); // if (newStream != null) { // for (Object f : fonts.keySet().toArray()) { // COSDictionary fontdata = (COSDictionary)fonts.getDictionaryObject((COSName)f); // if (getUniqueFontName(fontdata) != null) { // fonts.removeItem((COSName)f); // } // } // } } if (newStream == null) { PDFWriter writer = new PDFWriter(uniqueName, currentMCID); newStream = writer.writeText(pdStream); currentMCID = writer.getCurrentMCID(); } pdStream = new PDStream(sourceDoc, new ByteArrayInputStream(newStream.getBytes("ISO-8859-1"))); mergeXObj(sourcePageResources.getCOSObject(), fontinfo, uniqueName); PDFDictionary pageResources = (PDFDictionary) cloneForNewDocument(sourcePageResources.getCOSObject()); PDFDictionary fontDict = (PDFDictionary) pageResources.get("Font"); if (fontDict != null && pdfDoc.isMergeFontsEnabled()) { for (Map.Entry<String, Typeface> fontEntry : fontinfo.getUsedFonts().entrySet()) { Typeface font = fontEntry.getValue(); if (font instanceof FOPPDFFont) { FOPPDFFont pdfFont = (FOPPDFFont) font; if (pdfFont.getRef() == null) { pdfFont.setRef(new PDFDictionary()); pdfDoc.assignObjectNumber(pdfFont.getRef()); } fontDict.put(fontEntry.getKey(), pdfFont.getRef()); } } } updateXObj(sourcePageResources.getCOSObject(), pageResources); if (fontsBackup != null) { sourcePageResources.getCOSObject().setItem(COSName.FONT, fontsBackup); } COSStream originalPageContents = pdStream.getCOSObject(); bindOptionalContent(sourceDoc); PDFStream pageStream; Set filter; // if (originalPageContents instanceof COSStreamArray) { // COSStreamArray array = (COSStreamArray)originalPageContents; // pageStream = new PDFStream(); // InputStream in = array.getUnfilteredStream(); // OutputStream out = pageStream.getBufferOutputStream(); // IOUtils.copyLarge(in, out); // filter = FILTER_FILTER; // } else { pageStream = (PDFStream) cloneForNewDocument(originalPageContents); filter = Collections.EMPTY_SET; // } if (pageStream == null) { pageStream = new PDFStream(); } if (originalPageContents != null) { transferDict(originalPageContents, pageStream, filter); } transferPageDict(fonts, uniqueName, sourcePageResources); PDRectangle mediaBox = page.getMediaBox(); PDRectangle cropBox = page.getCropBox(); PDRectangle viewBox = cropBox != null ? cropBox : mediaBox; //Handle the /Rotation entry on the page dict int rotation = PDFUtil.getNormalizedRotation(page); //Transform to FOP's user space float w = (float) pos.getWidth() / 1000f; float h = (float) pos.getHeight() / 1000f; if (rotation == 90 || rotation == 270) { float tmp = w; w = h; h = tmp; } atdoc.setTransform(AffineTransform.getScaleInstance(w / viewBox.getWidth(), h / viewBox.getHeight())); atdoc.translate(0, viewBox.getHeight()); atdoc.rotate(-Math.PI); atdoc.scale(-1, 1); atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY()); rotate(rotation, viewBox, atdoc); StringBuilder boxStr = new StringBuilder(); boxStr.append(PDFNumber.doubleOut(mediaBox.getLowerLeftX())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getLowerLeftY())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getWidth())).append(' ') .append(PDFNumber.doubleOut(mediaBox.getHeight())).append(" re W n\n"); return boxStr.toString() + IOUtils.toString(pdStream.createInputStream(null), "ISO-8859-1"); }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
License:Apache License
private void moveAnnotations(PDPage page, List pageAnnotations, AffineTransform at) { PDRectangle mediaBox = page.getMediaBox(); PDRectangle cropBox = page.getCropBox(); PDRectangle viewBox = cropBox != null ? cropBox : mediaBox; for (Object obj : pageAnnotations) { PDAnnotation annot = (PDAnnotation) obj; PDRectangle rect = annot.getRectangle(); float translateX = (float) (at.getTranslateX() - viewBox.getLowerLeftX()); float translateY = (float) (at.getTranslateY() - viewBox.getLowerLeftY()); if (rect != null) { rect.setUpperRightX(rect.getUpperRightX() + translateX); rect.setLowerLeftX(rect.getLowerLeftX() + translateX); rect.setUpperRightY(rect.getUpperRightY() + translateY); rect.setLowerLeftY(rect.getLowerLeftY() + translateY); annot.setRectangle(rect);/*from w ww.j a v a2 s. c o m*/ } // COSArray vertices = (COSArray) annot.getCOSObject().getDictionaryObject("Vertices"); // if (vertices != null) { // Iterator iter = vertices.iterator(); // while (iter.hasNext()) { // COSFloat x = (COSFloat) iter.next(); // COSFloat y = (COSFloat) iter.next(); // x.setValue(x.floatValue() + translateX); // y.setValue(y.floatValue() + translateY); // } // } } }
From source file:org.apache.fop.render.pdf.pdfbox.PreloaderPDF.java
License:Apache License
private ImageInfo loadPDF(String uri, Source src, ImageContext context) throws IOException, ImageException { int selectedPage = ImageUtil.needPageIndexFromURI(uri); URI docURI = deriveDocumentURI(src.getSystemId()); PDDocument pddoc = getDocument(context, docURI, src); pddoc = Interceptors.getInstance().interceptOnLoad(pddoc, docURI); //Disable the warning about a missing close since we rely on the GC to decide when //the cached PDF shall be disposed off. pddoc.getDocument().setWarnMissingClose(false); int pageCount = pddoc.getNumberOfPages(); if (selectedPage < 0 || selectedPage >= pageCount) { throw new ImageException("Selected page (index: " + selectedPage + ") does not exist in the PDF file. The document has " + pddoc.getNumberOfPages() + " pages."); }//www.j ava2 s. c o m PDPage page = pddoc.getDocumentCatalog().getPages().get(selectedPage); PDRectangle mediaBox = page.getMediaBox(); PDRectangle cropBox = page.getCropBox(); PDRectangle viewBox = cropBox != null ? cropBox : mediaBox; int w = Math.round(viewBox.getWidth() * 1000); int h = Math.round(viewBox.getHeight() * 1000); //Handle the /Rotation entry on the page dict int rotation = PDFUtil.getNormalizedRotation(page); if (rotation == 90 || rotation == 270) { //Swap width and height int exch = w; w = h; h = exch; } ImageSize size = new ImageSize(); size.setSizeInMillipoints(w, h); size.setResolution(context.getSourceResolution()); size.calcPixelsFromSize(); ImageInfo info = new ImageInfo(uri, ImagePDF.MIME_PDF); info.setSize(size); info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, new ImagePDF(info, pddoc)); int lastPageIndex = pddoc.getNumberOfPages() - 1; if (selectedPage < lastPageIndex) { info.getCustomObjects().put(ImageInfo.HAS_MORE_IMAGES, Boolean.TRUE); } return info; }
From source file:org.data2semantics.annotate.D2S_SampleAnnotation.java
License:Apache License
/** * This will create a doucument showing various annotations. * //www . j a v a 2 s .com * @param args * The command line arguments. * * @throws Exception * If there is an error parsing the document. */ public static void main(String[] args) throws Exception { PDDocument document = new PDDocument(); try { PDPage page = new PDPage(); document.addPage(page); List annotations = page.getAnnotations(); // Setup some basic reusable objects/constants // Annotations themselves can only be used once! float inch = 72; PDGamma colourRed = new PDGamma(); colourRed.setR(1); PDGamma colourBlue = new PDGamma(); colourBlue.setB(1); PDGamma colourBlack = new PDGamma(); PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(inch / 12); // 12th inch PDBorderStyleDictionary borderThin = new PDBorderStyleDictionary(); borderThin.setWidth(inch / 72); // 1 point PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary(); borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE); borderULine.setWidth(inch / 72); // 1 point float pw = page.getMediaBox().getUpperRightX(); float ph = page.getMediaBox().getUpperRightY(); // First add some text, two lines we'll add some annotations to this // later PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.beginText(); contentStream.setFont(font, 18); contentStream.moveTextPositionByAmount(inch, ph - inch - 18); contentStream.drawString("PDFBox"); contentStream.moveTextPositionByAmount(0, -(inch / 2)); contentStream.drawString("Click Here"); contentStream.endText(); contentStream.close(); // Now add the markup annotation, a highlight to PDFBox text PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT); txtMark.setColour(colourBlue); txtMark.setConstantOpacity((float) 0.2); // Make the highlight 20% // transparent // Set the rectangle containing the markup float textWidth = (font.getStringWidth("PDFBox") / 1000) * 18; PDRectangle position = new PDRectangle(); position.setLowerLeftX(inch); position.setLowerLeftY(ph - inch - 18); position.setUpperRightX(72 + textWidth); position.setUpperRightY(ph - inch); txtMark.setRectangle(position); // work out the points forming the four corners of the annotations // set out in anti clockwise form (Completely wraps the text) // OK, the below doesn't match that description. // It's what acrobat 7 does and displays properly! float[] quads = new float[8]; quads[0] = position.getLowerLeftX(); // x1 quads[1] = position.getUpperRightY() - 2; // y1 quads[2] = position.getUpperRightX(); // x2 quads[3] = quads[1]; // y2 quads[4] = quads[0]; // x3 quads[5] = position.getLowerLeftY() - 2; // y3 quads[6] = quads[2]; // x4 quads[7] = quads[5]; // y5 txtMark.setQuadPoints(quads); txtMark.setContents("Highlighted since it's important"); annotations.add(txtMark); // Now add the link annotation, so the clickme works PDAnnotationLink txtLink = new PDAnnotationLink(); txtLink.setBorderStyle(borderULine); // Set the rectangle containing the link textWidth = (font.getStringWidth("Click Here") / 1000) * 18; position = new PDRectangle(); position.setLowerLeftX(inch); position.setLowerLeftY(ph - (float) (1.5 * inch) - 20); // down a // couple of // points position.setUpperRightX(72 + textWidth); position.setUpperRightY(ph - (float) (1.5 * inch)); txtLink.setRectangle(position); // add an action PDActionURI action = new PDActionURI(); action.setURI("http://www.pdfbox.org"); txtLink.setAction(action); annotations.add(txtLink); // Now draw a few more annotations PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_CIRCLE); aCircle.setContents("Circle Annotation"); aCircle.setInteriorColour(colourRed); // Fill in circle in red aCircle.setColour(colourBlue); // The border itself will be blue aCircle.setBorderStyle(borderThin); // Place the annotation on the page, we'll make this 1" round // 3" down, 1" in on the page position = new PDRectangle(); position.setLowerLeftX(inch); position.setLowerLeftY(ph - (3 * inch) - inch); // 1" height, 3" // down position.setUpperRightX(2 * inch); // 1" in, 1" width position.setUpperRightY(ph - (3 * inch)); // 3" down aCircle.setRectangle(position); // add to the annotations on the page annotations.add(aCircle); // Now a square annotation PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle( PDAnnotationSquareCircle.SUB_TYPE_SQUARE); aSquare.setContents("Square Annotation"); aSquare.setColour(colourRed); // Outline in red, not setting a fill aSquare.setBorderStyle(borderThick); // Place the annotation on the page, we'll make this 1" (72points) // square // 3.5" down, 1" in from the right on the page position = new PDRectangle(); // Reuse the variable, but note it's a // new object! position.setLowerLeftX(pw - (2 * inch)); // 1" in from right, 1" // wide position.setLowerLeftY(ph - (float) (3.5 * inch) - inch); // 1" height, 3.5" // down position.setUpperRightX(pw - inch); // 1" in from right position.setUpperRightY(ph - (float) (3.5 * inch)); // 3.5" down aSquare.setRectangle(position); // add to the annotations on the page annotations.add(aSquare); // Now we want to draw a line between the two, one end with an open // arrow PDAnnotationLine aLine = new PDAnnotationLine(); aLine.setEndPointEndingStyle(PDAnnotationLine.LE_OPEN_ARROW); aLine.setContents("Circle->Square"); aLine.setCaption(true); // Make the contents a caption on the line // Set the rectangle containing the line position = new PDRectangle(); // Reuse the variable, but note it's a // new object! position.setLowerLeftX(2 * inch); // 1" in + width of circle position.setLowerLeftY(ph - (float) (3.5 * inch) - inch); // 1" height, 3.5" // down position.setUpperRightX(pw - inch - inch); // 1" in from right, and // width of square position.setUpperRightY(ph - (3 * inch)); // 3" down (top of circle) aLine.setRectangle(position); // Now set the line position itself float[] linepos = new float[4]; linepos[0] = 2 * inch; // x1 = rhs of circle linepos[1] = ph - (float) (3.5 * inch); // y1 halfway down circle linepos[2] = pw - (2 * inch); // x2 = lhs of square linepos[3] = ph - (4 * inch); // y2 halfway down square aLine.setLine(linepos); aLine.setBorderStyle(borderThick); aLine.setColour(colourBlack); // add to the annotations on the page annotations.add(aLine); // Finally all done document.save("testAnnotation.pdf"); } finally { document.close(); } }
From source file:org.dspace.disseminate.CitationDocumentServiceImpl.java
License:BSD License
@Override public int drawStringWordWrap(PDPage page, PDPageContentStream contentStream, String text, int startX, int startY, PDFont pdfFont, float fontSize) throws IOException { float leading = 1.5f * fontSize; PDRectangle mediabox = page.getMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; List<String> lines = new ArrayList<>(); int lastSpace = -1; while (text.length() > 0) { int spaceIndex = text.indexOf(' ', lastSpace + 1); if (spaceIndex < 0) { lines.add(text);//from w ww.j a va2s .com text = ""; } else { String subString = text.substring(0, spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000; if (size > width) { if (lastSpace < 0) // So we have a word longer than the line... draw it anyways lastSpace = spaceIndex; subString = text.substring(0, lastSpace); lines.add(subString); text = text.substring(lastSpace).trim(); lastSpace = -1; } else { lastSpace = spaceIndex; } } } contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.moveTextPositionByAmount(startX, startY); int currentY = startY; for (String line : lines) { contentStream.drawString(line); currentY -= leading; contentStream.moveTextPositionByAmount(0, -leading); } contentStream.endText(); return currentY; }