List of usage examples for java.awt.geom AffineTransform rotate
public void rotate(double theta)
From source file:business.ImageManager.java
public ImageIcon getArrow(double angle) { BufferedImage img = new BufferedImage(40, 40, BufferedImage.TRANSLUCENT); Graphics2D big = img.createGraphics(); //setup para os rastros big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); big.setStroke(//from w w w.j a v a 2 s . c o m new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] { 5f }, 0f)); big.setColor(Color.red); int cx = this.getYellowBall().getIconWidth() / 2; int cy = this.getYellowBall().getIconHeight() / 2; AffineTransform at = AffineTransform.getTranslateInstance(cx, cy); at.rotate(Math.toRadians(angle)); // at.scale(2.0, 2.0); Shape shape = at.createTransformedShape(createArrow()); big.setPaint(Color.red); big.draw(shape); ImageIcon ret = new ImageIcon(img); return (ret); // tenta com o icone...angle. }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java
public void createAppearanceDictionary(PDFormXObject holderForml, PDSignatureField signatureField, float degrees) throws IOException { PDAppearanceDictionary appearance = new PDAppearanceDictionary(); appearance.getCOSObject().setDirect(true); PDAppearanceStream appearanceStream = new PDAppearanceStream(holderForml.getCOSStream()); AffineTransform transform = new AffineTransform(); transform.setToIdentity();// w w w. j av a 2 s . c om transform.rotate(Math.toRadians(degrees)); appearanceStream.setMatrix(transform); appearance.setNormalAppearance(appearanceStream); signatureField.getWidget().setAppearance(appearance); getStructure().setAppearanceDictionary(appearance); logger.debug("PDF appereance Dictionary has been created"); }
From source file:com.github.lindenb.jvarkit.tools.misc.BamCmpCoverage.java
@Override public Collection<Throwable> call() throws Exception { if (getOutputFile() == null) { return wrapException("output image file not defined"); }/*from w w w .ja va2 s . co m*/ if (this.imgageSize < 1) { return wrapException("Bad image size:" + this.imgageSize); } if (this.minDepth < 0) { return wrapException("Bad min depth : " + this.minDepth); } if (this.minDepth >= this.maxDepth) { return wrapException("Bad min<max depth : " + this.minDepth + "<" + this.maxDepth); } if (this.getBedFile() != null) { readBedFile(this.getBedFile()); } if (regionStr != null && this.intervals != null) { return wrapException("bed and interval both defined."); } final SamRecordFilter filter = new SamRecordFilter() { @Override public boolean filterOut(SAMRecord first, SAMRecord second) { return filterOut(first); } @Override public boolean filterOut(SAMRecord rec) { if (rec.getReadUnmappedFlag()) return true; if (rec.isSecondaryOrSupplementary()) return true; if (rec.getDuplicateReadFlag()) return true; if (rec.getNotPrimaryAlignmentFlag()) return true; if (rec.getReadFailsVendorQualityCheckFlag()) return true; if (rec.getMappingQuality() == 0) return true; /* ignore non-overlapping BED, already checked with QuertInterval if( intervals!=null && ! intervals.containsOverlapping( new Interval(rec.getReferenceName(), rec.getAlignmentStart(), rec.getAlignmentEnd())) ) { return true; } */ return false; } }; Set<File> files = new HashSet<File>(); try { SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT); srf.disable(SamReaderFactory.Option.EAGERLY_DECODE); srf.disable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS); srf.disable(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS); final List<String> args = this.getInputFiles(); for (String arg : args) { File f = new File(arg); if (f.getName().endsWith(".list")) { LOG.info("Reading BAM list from " + f); BufferedReader in = IOUtils.openFileForBufferedReading(f); String line; while ((line = in.readLine()) != null) { if (line.trim().isEmpty() || line.startsWith("#")) continue; files.add(new File(line)); } in.close(); } else { files.add(f); } } if (files.isEmpty()) { return wrapException("No BAM defined"); } Comparator<SAMRecord> comparator = new Comparator<SAMRecord>() { @Override public int compare(SAMRecord samRecord1, SAMRecord samRecord2) { final int refIndex1 = samRecord1.getReferenceIndex(); final int refIndex2 = samRecord2.getReferenceIndex(); if (refIndex1 == -1) { return (refIndex2 == -1 ? 0 : 1); } else if (refIndex2 == -1) { return -1; } final int cmp = refIndex1 - refIndex2; if (cmp != 0) { return cmp; } return samRecord1.getAlignmentStart() - samRecord2.getAlignmentStart(); } }; List<SamReader> readers = new ArrayList<SamReader>(files.size()); List<CloseableIterator<SAMRecord>> iterators = new ArrayList<CloseableIterator<SAMRecord>>( files.size()); Set<String> samples = new TreeSet<String>(); SAMSequenceDictionary dict = null; /* will be initialized below once, if needed */ QueryInterval queryIntervalArray[] = null; //scan samples names for (File bamFile : files) { SamReader r = srf.open(bamFile); readers.add(r); SAMFileHeader h = r.getFileHeader(); if (h.getSortOrder() != SortOrder.coordinate) { r.close(); return wrapException("file " + bamFile + " not sorted on coordinate"); } if (dict == null) { dict = h.getSequenceDictionary(); } else if (!SequenceUtil.areSequenceDictionariesEqual(dict, h.getSequenceDictionary())) { return wrapException("Found more than one dictint sequence dictionary"); } //fill query interval once List<QueryInterval> queryIntervals = new ArrayList<>(); if (regionStr != null && queryIntervalArray == null) { int colon = regionStr.indexOf(':'); String chrom; int chromStart; int chromEnd; if (colon == -1) { chrom = regionStr; } else { chrom = regionStr.substring(0, colon); } SAMSequenceRecord ssr = dict.getSequence(chrom); if (ssr == null) { return wrapException("Chromosome " + chrom + " not present in dictionary"); } int hyphen = regionStr.indexOf('-', colon + 1); if (hyphen != -1) { chromStart = Integer.parseInt(regionStr.substring(colon + 1, hyphen)); chromEnd = Integer.parseInt(regionStr.substring(hyphen + 1)); } else { chromStart = 0; chromEnd = ssr.getSequenceLength() - 1; } if (chromStart < 0 || chromEnd < chromStart) { return wrapException("bad position in " + regionStr); } queryIntervals.add(new QueryInterval(ssr.getSequenceIndex(), chromStart, chromEnd)); } if (this.intervals != null && queryIntervalArray == null) { for (Interval interval : this.intervals.keySet()) { SAMSequenceRecord ssr = dict.getSequence(interval.getContig()); if (ssr == null) { return wrapException( "Chromosome " + interval.getContig() + " not present in dictionary"); } queryIntervals.add( new QueryInterval(ssr.getSequenceIndex(), interval.getStart(), interval.getEnd())); } } if (!queryIntervals.isEmpty() && queryIntervalArray == null) { Collections.sort(queryIntervals); queryIntervalArray = queryIntervals.toArray(new QueryInterval[queryIntervals.size()]); } for (SAMReadGroupRecord rg : h.getReadGroups()) { String sample = rg.getSample(); if (sample == null) continue; samples.add(sample); } CloseableIterator<SAMRecord> reciterator = null; if (queryIntervalArray == null) { reciterator = r.iterator(); } else { reciterator = r.query(queryIntervalArray, false); } reciterator = new FilteringIterator(reciterator, filter); iterators.add(reciterator); } //free GC queryIntervalArray = null; LOG.info("Samples:" + samples.size()); for (String sample : samples) { this.sample2column.put(sample, this.sample2column.size()); } //create merging sam-reader MergingSamRecordIterator iter = new MergingSamRecordIterator(comparator, iterators); //create image LOG.info("Creating image " + this.imgageSize + "x" + this.imgageSize); this.image = new BufferedImage(this.imgageSize, this.imgageSize, BufferedImage.TYPE_INT_RGB); Graphics2D g = this.image.createGraphics(); this.marginWidth = this.imgageSize * 0.05; double drawingWidth = (this.imgageSize - 1) - marginWidth; this.sampleWidth = drawingWidth / samples.size(); //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); g.fillRect(0, 0, this.imgageSize, this.imgageSize); g.setColor(Color.BLACK); Hershey hershey = new Hershey(); for (String sample_x : samples) { double labelHeight = marginWidth; if (labelHeight > 50) labelHeight = 50; g.setColor(Color.BLACK); hershey.paint(g, sample_x, marginWidth + sample2column.get(sample_x) * sampleWidth, marginWidth - labelHeight, sampleWidth * 0.9, labelHeight * 0.9); AffineTransform old = g.getTransform(); AffineTransform tr = AffineTransform.getTranslateInstance(marginWidth, marginWidth + sample2column.get(sample_x) * sampleWidth); tr.rotate(Math.PI / 2); g.setTransform(tr); hershey.paint(g, sample_x, 0.0, 0.0, sampleWidth * 0.9, labelHeight * 0.9); //g.drawString(this.tabixFile.getFile().getName(),0,0); g.setTransform(old); for (String sample_y : samples) { Rectangle2D rect = new Rectangle2D.Double( marginWidth + sample2column.get(sample_x) * sampleWidth, marginWidth + sample2column.get(sample_y) * sampleWidth, sampleWidth, sampleWidth); g.setColor(Color.BLUE); g.draw(new Line2D.Double(rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY())); g.setColor(Color.BLACK); g.draw(rect); } } //ceate bit-array BitSampleMatrix bitMatrix = new BitSampleMatrix(samples.size()); //preivous chrom //int prev_tid=-1; BufferedList<Depth> depthList = new BufferedList<Depth>(); g.setColor(Color.BLACK); SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict); LOG.info("Scanning bams..."); while (iter.hasNext()) { SAMRecord rec = iter.next(); if (filter.filterOut(rec)) continue; progress.watch(rec); SAMReadGroupRecord gr = rec.getReadGroup(); if (gr == null) continue; String sample = gr.getSample(); if (sample == null) continue; int sample_id = this.sample2column.get(sample); Cigar cigar = rec.getCigar(); if (cigar == null) continue; int refPos = rec.getAlignmentStart(); /* cleanup front pos */ while (!depthList.isEmpty()) { Depth front = depthList.getFirst(); if (front.tid != rec.getReferenceIndex().intValue() || front.pos < refPos) { paint(bitMatrix, front); depthList.removeFirst(); continue; } else { break; } } for (CigarElement ce : cigar.getCigarElements()) { CigarOperator op = ce.getOperator(); if (!op.consumesReferenceBases()) continue; if (op.consumesReadBases()) { for (int i = 0; i < ce.getLength(); ++i) { Depth depth = null; int pos = refPos + i; //ignore non-overlapping BED if (this.intervals != null && !this.intervals .containsOverlapping(new Interval(rec.getReferenceName(), pos, pos))) { continue; } else if (depthList.isEmpty()) { depth = new Depth(); depth.pos = pos; depth.tid = rec.getReferenceIndex(); depthList.add(depth); } else if (depthList.getLast().pos < pos) { Depth prev = depthList.getLast(); while (prev.pos < pos) { depth = new Depth(); depth.pos = prev.pos + 1; depth.tid = rec.getReferenceIndex(); depthList.add(depth); prev = depth; } depth = prev; } else { int lastPos = depthList.get(depthList.size() - 1).pos; int distance = lastPos - pos; int indexInList = (depthList.size() - 1) - (distance); if (indexInList < 0) { //can appen when BED declared and partially overlap the read continue; } depth = depthList.get((depthList.size() - 1) - (distance)); if (depth.pos != pos) { return wrapException(" " + pos + " vs " + depth.pos + " " + lastPos); } } depth.depths[sample_id]++; } } refPos += ce.getLength(); } } while (!depthList.isEmpty()) { //paint(g,depthList.remove(0)); paint(bitMatrix, depthList.remove(0)); } progress.finish(); iter.close(); //paint bitset for (int x = 0; x < bitMatrix.n_samples; ++x) { for (int y = 0; y < bitMatrix.n_samples; ++y) { LOG.info("Painting...(" + x + "/" + y + ")"); paint(g, bitMatrix.get(x, y)); } } g.dispose(); //close readers for (SamReader r : readers) r.close(); //save file LOG.info("saving " + getOutputFile()); if (getOutputFile().getName().toLowerCase().endsWith(".png")) { ImageIO.write(this.image, "PNG", getOutputFile()); } else { ImageIO.write(this.image, "JPG", getOutputFile()); } return Collections.emptyList(); } catch (Exception err) { return wrapException(err); } finally { } }
From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java
/** * This is used for the arrow of a directed and for one of the * arrows for non-directed edges//www .j av a 2 s . c o m * Get a transform to place the arrow shape on the passed edge at the * point where it intersects the passed shape * @param edgeShape * @param vertexShape * @return */ public AffineTransform getArrowTransform(Line2D edgeShape, Shape vertexShape) { float dx = (float) (edgeShape.getX1() - edgeShape.getX2()); float dy = (float) (edgeShape.getY1() - edgeShape.getY2()); // iterate over the line until the edge shape will place the // arrowhead closer than 'arrowGap' to the vertex shape boundary while ((dx * dx + dy * dy) > arrow_placement_tolerance) { try { edgeShape = getLastOutsideSegment(edgeShape, vertexShape); } catch (IllegalArgumentException e) { System.err.println(e.toString()); return null; } dx = (float) (edgeShape.getX1() - edgeShape.getX2()); dy = (float) (edgeShape.getY1() - edgeShape.getY2()); } double atheta = Math.atan2(dx, dy) + Math.PI / 2; AffineTransform at = AffineTransform.getTranslateInstance(edgeShape.getX1(), edgeShape.getY1()); at.rotate(-atheta); return at; }
From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java
/** * This is used for the reverse-arrow of a non-directed edge * get a transform to place the arrow shape on the passed edge at the * point where it intersects the passed shape * @param edgeShape//from w w w . j a va 2 s .co m * @param vertexShape * @return */ protected AffineTransform getReverseArrowTransform(Line2D edgeShape, Shape vertexShape) { float dx = (float) (edgeShape.getX1() - edgeShape.getX2()); float dy = (float) (edgeShape.getY1() - edgeShape.getY2()); // iterate over the line until the edge shape will place the // arrowhead closer than 'arrowGap' to the vertex shape boundary while ((dx * dx + dy * dy) > arrow_placement_tolerance) { try { edgeShape = getFirstOutsideSegment(edgeShape, vertexShape); } catch (IllegalArgumentException e) { System.err.println(e.toString()); return null; } dx = (float) (edgeShape.getX1() - edgeShape.getX2()); dy = (float) (edgeShape.getY1() - edgeShape.getY2()); } // calculate the angle for the arrowhead double atheta = Math.atan2(dx, dy) - Math.PI / 2; AffineTransform at = AffineTransform.getTranslateInstance(edgeShape.getX1(), edgeShape.getY1()); at.rotate(-atheta); return at; }
From source file:edu.uci.ics.jung.visualization.picking.ShapePickSupport.java
/** * Retrieves the shape template for <code>e</code> and * transforms it according to the positions of its endpoints * in <code>layout</code>.//from w ww . jav a 2 s . c o m * @param layout the <code>Layout</code> which specifies * <code>e</code>'s endpoints' positions * @param e the edge whose shape is to be returned * @return */ private Shape getTransformedEdgeShape(Layout<V, E> layout, E e) { Pair<V> pair = layout.getGraph().getEndpoints(e); V v1 = pair.getFirst(); V v2 = pair.getSecond(); boolean isLoop = v1.equals(v2); Point2D p1 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v1)); Point2D p2 = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v2)); if (p1 == null || p2 == null) return null; float x1 = (float) p1.getX(); float y1 = (float) p1.getY(); float x2 = (float) p2.getX(); float y2 = (float) p2.getY(); // translate the edge to the starting vertex AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1); Shape edgeShape = vv.getRenderContext().getEdgeShapeTransformer() .transform(Context.<Graph<V, E>, E>getInstance(vv.getGraphLayout().getGraph(), e)); if (isLoop) { // make the loops proportional to the size of the vertex Shape s2 = vv.getRenderContext().getVertexShapeTransformer().transform(v2); Rectangle2D s2Bounds = s2.getBounds2D(); xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight()); // move the loop so that the nadir is centered in the vertex xform.translate(0, -edgeShape.getBounds2D().getHeight() / 2); } else { float dx = x2 - x1; float dy = y2 - y1; // rotate the edge to the angle between the vertices double theta = Math.atan2(dy, dx); xform.rotate(theta); // stretch the edge to span the distance between the vertices float dist = (float) Math.sqrt(dx * dx + dy * dy); xform.scale(dist, 1.0f); } // transform the edge to its location and dimensions edgeShape = xform.createTransformedShape(edgeShape); return edgeShape; }
From source file:org.jfree.experimental.swt.SWTGraphics2D.java
/** * Applies a rotation transform.// w w w.j av a2 s. c o m * * @param theta the angle of rotation. */ public void rotate(double theta) { AffineTransform t = getTransform(); t.rotate(theta); setTransform(t); }
From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java
/** * Labels the specified non-self-loop edge with the specified label. * Uses the font specified by this instance's * <code>EdgeFontFunction</code>. (If the font is unspecified, the existing * font for the graphics context is used.) Positions the * label between the endpoints according to the coefficient returned * by this instance's edge label closeness function. *//*from w ww. j av a 2 s . c o m*/ protected void labelEdge(Graphics2D g2d, Edge e, String label, int x1, int x2, int y1, int y2) { int distX = x2 - x1; int distY = y2 - y1; double totalLength = Math.sqrt(distX * distX + distY * distY); double closeness = edgeLabelClosenessFunction.getNumber(e).doubleValue(); int posX = (int) (x1 + (closeness) * distX); int posY = (int) (y1 + (closeness) * distY); int xDisplacement = (int) (LABEL_OFFSET * (distY / totalLength)); int yDisplacement = (int) (LABEL_OFFSET * (-distX / totalLength)); Component component = prepareRenderer(graphLabelRenderer, label, isPicked(e), e); Dimension d = component.getPreferredSize(); Shape edgeShape = edgeShapeFunction.getShape(e); double parallelOffset = 1; parallelOffset += parallelEdgeIndexFunction.getIndex(e); if (edgeShape instanceof Ellipse2D) { parallelOffset += edgeShape.getBounds().getHeight(); parallelOffset = -parallelOffset; } parallelOffset *= d.height; AffineTransform old = g2d.getTransform(); AffineTransform xform = new AffineTransform(old); xform.translate(posX + xDisplacement, posY + yDisplacement); double dx = x2 - x1; double dy = y2 - y1; if (graphLabelRenderer.isRotateEdgeLabels()) { double theta = Math.atan2(dy, dx); if (dx < 0) { theta += Math.PI; } xform.rotate(theta); } if (dx < 0) { parallelOffset = -parallelOffset; } xform.translate(-d.width / 2, -(d.height / 2 - parallelOffset)); g2d.setTransform(xform); rendererPane.paintComponent(g2d, component, screenDevice, 0, 0, d.width, d.height, true); g2d.setTransform(old); }
From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java
/** * Draws the edge <code>e</code>, whose endpoints are at <code>(x1,y1)</code> * and <code>(x2,y2)</code>, on the graphics context <code>g</code>. * The <code>Shape</code> provided by the <code>EdgeShapeFunction</code> instance * is scaled in the x-direction so that its width is equal to the distance between * <code>(x1,y1)</code> and <code>(x2,y2)</code>. *///w w w. j a v a 2 s. co m protected void drawSimpleEdge(Graphics2D g, Edge e, int x1, int y1, int x2, int y2) { Pair endpoints = e.getEndpoints(); Vertex v1 = (Vertex) endpoints.getFirst(); Vertex v2 = (Vertex) endpoints.getSecond(); boolean isLoop = v1.equals(v2); Shape s2 = vertexShapeFunction.getShape(v2); Shape edgeShape = edgeShapeFunction.getShape(e); boolean edgeHit = true; boolean arrowHit = true; Rectangle deviceRectangle = null; if (screenDevice != null) { Dimension d = screenDevice.getSize(); if (d.width <= 0 || d.height <= 0) { d = screenDevice.getPreferredSize(); } deviceRectangle = new Rectangle(0, 0, d.width, d.height); } AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1); if (isLoop) { // this is a self-loop. scale it is larger than the vertex // it decorates and translate it so that its nadir is // at the center of the vertex. Rectangle2D s2Bounds = s2.getBounds2D(); xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight()); xform.translate(0, -edgeShape.getBounds2D().getWidth() / 2); } else { // this is a normal edge. Rotate it to the angle between // vertex endpoints, then scale it to the distance between // the vertices float dx = x2 - x1; float dy = y2 - y1; float thetaRadians = (float) Math.atan2(dy, dx); xform.rotate(thetaRadians); float dist = (float) Math.sqrt(dx * dx + dy * dy); xform.scale(dist, 1.0); } edgeShape = xform.createTransformedShape(edgeShape); edgeHit = viewTransformer.transform(edgeShape).intersects(deviceRectangle); if (edgeHit == true) { Paint oldPaint = g.getPaint(); // get Paints for filling and drawing // (filling is done first so that drawing and label use same Paint) Paint fill_paint = edgePaintFunction.getFillPaint(e); if (fill_paint != null) { g.setPaint(fill_paint); g.fill(edgeShape); } Paint draw_paint = edgePaintFunction.getDrawPaint(e); if (draw_paint != null) { g.setPaint(draw_paint); g.draw(edgeShape); } float scalex = (float) g.getTransform().getScaleX(); float scaley = (float) g.getTransform().getScaleY(); // see if arrows are too small to bother drawing if (scalex < .3 || scaley < .3) return; if (edgeArrowPredicate.evaluate(e)) { Shape destVertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getSecond()); AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2); destVertexShape = xf.createTransformedShape(destVertexShape); arrowHit = viewTransformer.transform(destVertexShape).intersects(deviceRectangle); if (arrowHit) { AffineTransform at; if (edgeShape instanceof GeneralPath) at = getArrowTransform((GeneralPath) edgeShape, destVertexShape); else at = getArrowTransform(new GeneralPath(edgeShape), destVertexShape); if (at == null) return; Shape arrow = edgeArrowFunction.getArrow(e); arrow = at.createTransformedShape(arrow); // note that arrows implicitly use the edge's draw paint g.fill(arrow); } if (e instanceof UndirectedEdge) { Shape vertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getFirst()); xf = AffineTransform.getTranslateInstance(x1, y1); vertexShape = xf.createTransformedShape(vertexShape); arrowHit = viewTransformer.transform(vertexShape).intersects(deviceRectangle); if (arrowHit) { AffineTransform at; if (edgeShape instanceof GeneralPath) at = getReverseArrowTransform((GeneralPath) edgeShape, vertexShape, !isLoop); else at = getReverseArrowTransform(new GeneralPath(edgeShape), vertexShape, !isLoop); if (at == null) return; Shape arrow = edgeArrowFunction.getArrow(e); arrow = at.createTransformedShape(arrow); g.fill(arrow); } } } // use existing paint for text if no draw paint specified if (draw_paint == null) g.setPaint(oldPaint); String label = edgeStringer.getLabel(e); if (label != null) { labelEdge(g, e, label, x1, x2, y1, y2); } // restore old paint g.setPaint(oldPaint); } }
From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java
/** * 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 ww . j a v a 2 s. 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"); }