List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getHeight
public float getHeight()
From source file:de.redsix.pdfcompare.PdfComparator.java
License:Apache License
public static ImageWithDimension renderPageAsImage(final PDDocument document, final PDFRenderer expectedPdfRenderer, final int pageIndex) throws IOException { final BufferedImage bufferedImage = expectedPdfRenderer.renderImageWithDPI(pageIndex, DPI); final PDRectangle mediaBox = document.getPage(pageIndex).getMediaBox(); return new ImageWithDimension(bufferedImage, mediaBox.getWidth(), mediaBox.getHeight()); }
From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D.java
License:Apache License
PdfBoxGraphics2D(PDDocument document, PDRectangle bbox, PdfBoxGraphics2D parentGfx) throws IOException { this.document = document; this.bbox = bbox; PDAppearanceStream appearance = new PDAppearanceStream(document); xFormObject = appearance;//from w w w .jav a 2 s.c o m xFormObject.setResources(new PDResources()); xFormObject.setBBox(bbox); contentStream = new PDPageContentStream(document, appearance, xFormObject.getStream().createOutputStream(COSName.FLATE_DECODE)); contentStreamSaveState(); if (parentGfx != null) { this.colorMapper = parentGfx.colorMapper; this.fontTextDrawer = parentGfx.fontTextDrawer; this.imageEncoder = parentGfx.imageEncoder; this.paintApplier = parentGfx.paintApplier; } baseTransform = new AffineTransform(); baseTransform.translate(0, bbox.getHeight()); baseTransform.scale(1, -1); calcImage = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR); calcGfx = calcImage.createGraphics(); font = calcGfx.getFont(); copyInfo = null; }
From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D.java
License:Apache License
private void applyShadingAsColor(PDShading shading) throws IOException { /*//from ww w . jav a 2 s . co m * If the paint has a shading we must create a tiling pattern and set that as * stroke color... */ PDTilingPattern pattern = new PDTilingPattern(); pattern.setPaintType(PDTilingPattern.PAINT_COLORED); pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING); PDRectangle anchorRect = bbox; pattern.setBBox(anchorRect); pattern.setXStep(anchorRect.getWidth()); pattern.setYStep(anchorRect.getHeight()); PDAppearanceStream appearance = new PDAppearanceStream(this.document); appearance.setResources(pattern.getResources()); appearance.setBBox(pattern.getBBox()); PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance, ((COSStream) pattern.getCOSObject()).createOutputStream()); imageContentStream.addRect(0, 0, anchorRect.getWidth(), anchorRect.getHeight()); imageContentStream.clip(); imageContentStream.shadingFill(shading); imageContentStream.close(); PDColorSpace patternCS1 = new PDPattern(null); COSName tilingPatternName = xFormObject.getResources().add(pattern); PDColor patternColor = new PDColor(tilingPatternName, patternCS1); contentStream.setNonStrokingColor(patternColor); contentStream.setStrokingColor(patternColor); }
From source file:de.uni_siegen.wineme.come_in.thumbnailer.thumbnailers.PDFBoxThumbnailer.java
License:Open Source License
private BufferedImage convertToImage(final PDPage page, final int imageType, final int thumbWidth, final int thumbHeight)/* */ throws IOException /* */ {// w ww.j a v a2 s .co m /* 707 */ final PDRectangle mBox = page.findMediaBox(); /* 708 */ final float widthPt = mBox.getWidth(); /* 709 */ final float heightPt = mBox.getHeight(); /* 711 */ final int widthPx = thumbWidth; // Math.round(widthPt * scaling); /* 712 */ final int heightPx = thumbHeight; // Math.round(heightPt * scaling); /* 710 */ final double scaling = Math.min((double) thumbWidth / widthPt, (double) thumbHeight / heightPt); // resolution / 72.0F; /* */ /* 714 */ final Dimension pageDimension = new Dimension((int) widthPt, (int) heightPt); /* */ /* 716 */ final BufferedImage retval = new BufferedImage(widthPx, heightPx, imageType); /* 717 */ final Graphics2D graphics = (Graphics2D) retval.getGraphics(); /* 718 */ graphics.setBackground(PDFBoxThumbnailer.TRANSPARENT_WHITE); /* 719 */ graphics.clearRect(0, 0, retval.getWidth(), retval.getHeight()); /* 720 */ graphics.scale(scaling, scaling); /* 721 */ final PageDrawer drawer = new PageDrawer(); /* 722 */ drawer.drawPage(graphics, page, pageDimension); /* */ try /* */ { /* 728 */ final int rotation = page.findRotation(); /* 729 */ if (rotation == 90 || rotation == 270) /* */ { /* 731 */ final int w = retval.getWidth(); /* 732 */ final int h = retval.getHeight(); /* 733 */ final BufferedImage rotatedImg = new BufferedImage(w, h, retval.getType()); /* 734 */ final Graphics2D g = rotatedImg.createGraphics(); /* 735 */ g.rotate(Math.toRadians(rotation), w / 2, h / 2); /* 736 */ g.drawImage(retval, null, 0, 0); /* */ } /* */ } /* */ catch (final ImagingOpException e) /* */ { /* 741 */ //log.warn("Unable to rotate page image", e); /* */ } /* */ /* 744 */ return retval; /* */ }
From source file:edworld.pdfreader4humans.impl.MainPDFComponentLocator.java
License:Apache License
protected List<GridComponent> locateAllGridComponents(PDPage page) throws IOException { final PDPage pageToDraw = page; return new PageDrawer() { private List<GridComponent> list = new ArrayList<GridComponent>(); public List<GridComponent> locateGridComponents() throws IOException { PDRectangle cropBox = pageToDraw.findCropBox(); BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth()), Math.round(cropBox.getHeight()), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); drawPage(graphics, pageToDraw, cropBox.createDimension()); graphics.dispose();//ww w. j av a 2s. co m dispose(); Collections.sort(list); return list; } @Override protected void processOperator(PDFOperator operator, List<COSBase> arguments) throws IOException { processGridOPeration(operator, arguments); } private void processGridOPeration(PDFOperator operator, List<COSBase> arguments) throws IOException { if (isTextOperation(operator.getOperation())) return; if (operator.getOperation().equals("i")) { processSetFlatnessTolerance((COSNumber) arguments.get(0)); return; } if (operator.getOperation().equals("l")) processLineTo((COSNumber) arguments.get(0), (COSNumber) arguments.get(1)); else if (operator.getOperation().equals("re")) processAppendRectangleToPath((COSNumber) arguments.get(0), (COSNumber) arguments.get(1), (COSNumber) arguments.get(2), (COSNumber) arguments.get(3)); super.processOperator(operator, arguments); } private void processSetFlatnessTolerance(COSNumber flatnessTolerance) { getGraphicsState().setFlatness(flatnessTolerance.doubleValue()); } private void processLineTo(COSNumber x, COSNumber y) { Point2D from = getLinePath().getCurrentPoint(); Point2D to = transformedPoint(x.doubleValue(), y.doubleValue()); addGridComponent("line", from, to); } private void processAppendRectangleToPath(COSNumber x, COSNumber y, COSNumber w, COSNumber h) { Point2D from = transformedPoint(x.doubleValue(), y.doubleValue()); Point2D to = transformedPoint(w.doubleValue() + x.doubleValue(), h.doubleValue() + y.doubleValue()); addGridComponent("rect", from, to); } private void addGridComponent(String type, Point2D from, Point2D to) { float fromX = (float) Math.min(from.getX(), to.getX()); float fromY = (float) Math.min(from.getY(), to.getY()); float toX = (float) Math.max(from.getX(), to.getX()); float toY = (float) Math.max(from.getY(), to.getY()); list.add(new GridComponent(type, fromX, fromY, toX, toY, getGraphicsState().getLineWidth())); } private boolean isTextOperation(String operation) { return "/BT/ET/T*/Tc/Td/TD/Tf/Tj/TJ/TL/Tm/Tr/Ts/Tw/Tz/'/\"/".contains("/" + operation + "/"); } }.locateGridComponents(); }
From source file:edworld.pdfreader4humans.PDFReader.java
License:Apache License
public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor, boolean showStructure) throws IOException { Map<String, Font> fonts = new HashMap<String, Font>(); PDRectangle cropBox = getPageCropBox(pageNumber); BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling), Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setBackground(backgroundColor); graphics.clearRect(0, 0, image.getWidth(), image.getHeight()); graphics.setColor(backgroundColor);// w ww. j a v a 2s .c om graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); graphics.setColor(inkColor); graphics.scale(scaling, scaling); for (Component component : getFirstLevelComponents(pageNumber)) draw(component, graphics, inkColor, backgroundColor, showStructure, fonts); graphics.dispose(); return image; }
From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java
License:Apache License
/** * creates a sample document with some text using a text matrix. * //from w w w . j a v a 2s .co m * @param message * The message to write in the file. * @param outfile * The resulting PDF. * * @throws IOException * If there is an error writing the data. * @throws COSVisitorException * If there is an error writing the PDF. */ public void doIt(String message, String outfile) throws IOException, COSVisitorException { // the document PDDocument doc = null; try { doc = new PDDocument(); // Page 1 PDFont font = PDType1Font.HELVETICA; PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); float fontSize = 12.0f; PDRectangle pageSize = page.findMediaBox(); System.err.println("pageSize " + pageSize); System.err.println( "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54); float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f; float stringWidth = font.getStringWidth(message); float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f; PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // counterclockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition); contentStream.drawString(message + " " + i); } // clockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 2 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // text scaling for (int i = 0; i < 10; i++) { contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 3 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); int i = 0; // text scaling combined with rotation contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.endText(); contentStream.close(); // Page 4 { page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); AffineTransform root = new AffineTransform(); root.scale(72.0 / 2.54, 72.0 / 2.54); for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) { // text scaling combined with rotation { AffineTransform rowMatrix = new AffineTransform(root); rowMatrix.translate(1, i); contentStream.setTextMatrix(rowMatrix); contentStream.drawString(message + " " + i); } } contentStream.endText(); contentStream.close(); } doc.save(outfile); } finally { if (doc != null) { doc.close(); } } }
From source file:gamma.cvd.calculator.print.CVDPrint.java
private PDDocument createPdfDocument(CVDPatient patient) throws IOException { PDDocument document = new PDDocument(); List<PDPage> pageList = new ArrayList<>(); PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4); pageList.add(page1);//ww w . ja v a 2 s .c om PDRectangle rect = pageList.get(0).getMediaBox(); document.addPage(pageList.get(0)); PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD; PDFont fontCourier = PDType1Font.COURIER; PDFont fontCourierBold = PDType1Font.COURIER_BOLD; PDPageContentStream contentStream = new PDPageContentStream(document, pageList.get(0)); line = 0; contentStream.beginText(); contentStream.setFont(fontHelveticaBold, 18); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace); contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName()); contentStream.endText(); contentStream.setFont(fontCourier, 12); writeLine("Patient no.:", String.valueOf(patient.getPatientId()), contentStream, rect.getHeight() - patientLineSpace); writeLine("First name:", patient.getFirstName(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Last name:", patient.getLastName(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Date of birth:", patient.getBirthdate().toString(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Sex:", String.valueOf(patient.getSex()), contentStream, rect.getHeight() - patientLineSpace); int n = 0; for (CVDRiskData data : patient.getRiskData()) { if (n > 0 && n % 3 == 0) { contentStream.close(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A4); pageList.add(page); document.addPage(pageList.get(n / 3)); contentStream = new PDPageContentStream(document, pageList.get(n / 3)); line = 0; contentStream.beginText(); contentStream.setFont(fontHelveticaBold, 18); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace); contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName() + ", page " + ((n / 3) + 1)); contentStream.endText(); } contentStream.beginText(); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - testDataLineSpace - lineSpace * ++line); contentStream.endText(); contentStream.setFont(fontCourierBold, 12); writeLine("Test ID:", String.valueOf(data.getTestId()), contentStream, rect.getHeight() - testDataLineSpace); contentStream.setFont(fontCourier, 12); writeLine("Test date:", data.getTestDate().toString(), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Cholesterol type:", data.getCholesterolType(), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Cholesterol mmol/L:", String.format("%.2f", data.getCholesterolMmolL()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("HDL mmol/L:", String.format("%.2f", data.getHdlMmolL()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Diastolic blood pressure:", String.valueOf(data.getBloodPressureDiastolicMmHg()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Systolic blood pressure:", String.valueOf(data.getBloodPressureSystolicMmHg()), contentStream, rect.getHeight() - testDataLineSpace); if (data.isSmoker()) { writeLine("Patient is smoker:", "Yes", contentStream, rect.getHeight() - testDataLineSpace); } else { writeLine("Patient is smoker:", "No", contentStream, rect.getHeight() - testDataLineSpace); } if (data.isDiabetic()) { writeLine("Patient is diabetic:", "Yes", contentStream, rect.getHeight() - testDataLineSpace); } else { writeLine("Patient is diabetic:", "No", contentStream, rect.getHeight() - testDataLineSpace); } int score = data.calculateRiskScore(); writeLine("Risk score:", String.valueOf(score), contentStream, rect.getHeight() - testDataLineSpace); int riskPercentage = data.getRiskPercentage(score); writeLine("Risk percentage:", new StringBuilder().append(riskPercentage).append(" %").toString(), contentStream, rect.getHeight() - testDataLineSpace); n++; } contentStream.close(); return document; }
From source file:info.informationsea.venn.graphics.VennDrawPDF.java
License:Open Source License
public static <T> void draw(VennFigure<T> vennFigure, PDDocument doc, PDPage page, PDFont font, PDRectangle rect) throws IOException { PDPageContentStream contents = new PDPageContentStream(doc, page); Rectangle2D drawRect = vennFigure.drawRect(str -> stringBoundingBox(font, str, FONT_SIZE)); PointConverter.JoinedConverter pointConverter = new PointConverter.JoinedConverter(); pointConverter/*from ww w .ja va 2s. co m*/ .addLast(new PointConverter.Translate(-drawRect.getMinX() + MARGIN, -drawRect.getMinY() + MARGIN)); pointConverter.addLast(new PointConverter.Scale(1, -1)); pointConverter.addLast(new PointConverter.Translate(0, rect.getHeight())); // fill first for (VennFigure.Shape<T> shape : vennFigure.getShapes()) { if (shape instanceof VennFigure.Oval) { VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape; Color fillColor = VennDrawGraphics2D.decodeColor(oval.getColor()); if (fillColor.getAlpha() == 0) continue; //COSName graphicsStateName = page.getResources().add(graphicsState); List<VennFigure.Point> polygon = oval.toPolygon(); VennFigure.Point converted = pointConverter.convert(polygon.get(0)); contents.moveTo((float) converted.getX(), (float) converted.getY()); polygon.add(polygon.remove(0)); // move to last for (VennFigure.Point p : polygon) { converted = pointConverter.convert(p); contents.lineTo((float) converted.getX(), (float) converted.getY()); } if (fillColor.getAlpha() != 255) { PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); graphicsState.setNonStrokingAlphaConstant(fillColor.getAlpha() / 255.f); contents.saveGraphicsState(); contents.setGraphicsStateParameters(graphicsState); } contents.setNonStrokingColor(fillColor); contents.fill(); if (fillColor.getAlpha() != 255) { contents.restoreGraphicsState(); } } } for (VennFigure.Shape<T> shape : vennFigure.getShapes()) { if (shape instanceof VennFigure.Oval) { VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape; List<VennFigure.Point> polygon = oval.toPolygon(); VennFigure.Point converted = pointConverter.convert(polygon.get(0)); contents.moveTo((float) converted.getX(), (float) converted.getY()); polygon.add(polygon.remove(0)); // move to last for (VennFigure.Point p : polygon) { converted = pointConverter.convert(p); contents.lineTo((float) converted.getX(), (float) converted.getY()); } contents.setNonStrokingColor(Color.BLACK); contents.stroke(); } else if (shape instanceof VennFigure.Text) { VennFigure.Text<T> text = (VennFigure.Text<T>) shape; Rectangle2D boundingBox = stringBoundingBox(font, text.getText(), FONT_SIZE); VennFigure.Point converted = pointConverter.convert(text.getCenter()); float xOffset; switch (text.getJust()) { case CENTER: xOffset = (float) (-boundingBox.getWidth() / 2); break; case RIGHT: xOffset = (float) (-boundingBox.getWidth()); break; default: xOffset = 0; break; } contents.beginText(); contents.setNonStrokingColor(Color.BLACK); contents.setFont(font, FONT_SIZE); contents.newLineAtOffset((float) (converted.getX() + xOffset), (float) (converted.getY() - boundingBox.getHeight() / 2)); contents.showText(text.getText()); contents.endText(); } } contents.saveGraphicsState(); contents.close(); }
From source file:javaexample.RadialTextPdf.java
License:Open Source License
private void generatePage(PDDocument document) throws IOException { // Creates a new page. PDPage page = new PDPage(pageRect); document.addPage(page);/*from w w w . j a va2s . c om*/ // Gets boundings of the page. PDRectangle rect = page.getMediaBox(); // Calculates the side of the square that fits into the page. float squareSide = Math.min(rect.getWidth(), rect.getHeight()); // Calculates the center point of the page. float centerX = (rect.getLowerLeftX() + rect.getUpperRightX()) / 2; float centerY = (rect.getLowerLeftY() + rect.getUpperRightY()) / 2; PDPageContentStream cos = new PDPageContentStream(document, page); // Creates the font for the radial text. PDFont font = PDType1Font.HELVETICA_BOLD; // Standard font float fontSize = squareSide / 30; float fontAscent = font.getFontDescriptor().getAscent() / 1000 * fontSize; // Calculates key values for the drawings. float textX = squareSide / 3.4F; // x of the text. float textY = -fontAscent / 2; // y of the text (for vertical centering of text). float lineToX = textX * 0.97F; // x destination for the line. float lineWidth = squareSide / 900; // width of lines. // Moves the origin (0,0) of the axes to the center of the page. cos.concatenate2CTM(AffineTransform.getTranslateInstance(centerX, centerY)); for (float degrees = 0; degrees < 360; degrees += 7.5) { double radians = degrees2Radians(degrees); // Creates a pure color with the hue based on the angle. Color textColor = Color.getHSBColor(degrees / 360.0F, 1, 1); // Saves the graphics state because the angle changes on each iteration. cos.saveGraphicsState(); // Rotates the axes by the angle expressed in radians. cos.concatenate2CTM(AffineTransform.getRotateInstance(radians)); // Draws a line from the center of the page. cos.setLineWidth(lineWidth); cos.moveTo(0, 0); cos.lineTo(lineToX, 0); cos.stroke(); // Draws the radial text. cos.beginText(); cos.setNonStrokingColor(textColor); cos.setFont(font, fontSize); cos.moveTextPositionByAmount(textX, textY); cos.drawString("PDF"); cos.endText(); // Restores the graphics state to remove rotation transformation. cos.restoreGraphicsState(); } cos.close(); }