List of usage examples for com.lowagie.text Rectangle getHeight
public float getHeight()
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * /*from w w w. ja v a 2s . c o m*/ * This method for Decorating the PDF with watermark. * * @param watermarkPdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file * for decoration */ private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) { watermarkPdfStamper.setFormFlattening(true); PdfReader pdfReader = watermarkPdfStamper.getReader(); int pageCount = pdfReader.getNumberOfPages(); int pdfPageNumber = 0; PdfContentByte pdfContents; Rectangle rectangle; while (pdfPageNumber < pageCount) { pdfPageNumber++; pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber); rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber); if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { decoratePdfWatermarkImage(pdfContents, (int) rectangle.getWidth(), (int) rectangle.getHeight(), watermarkBean); } if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { decoratePdfWatermarkText(pdfContents, rectangle, watermarkBean); } watermarkPdfStamper.setFormFlattening(true); } try { watermarkPdfStamper.close(); } catch (IOException decorateWatermark) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + decorateWatermark.getMessage()); } catch (DocumentException documentException) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + documentException.getMessage()); } }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * This method is for setting the properties of watermark Text. *//*ww w. j a v a2s . c om*/ private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, Rectangle rectangle, WatermarkBean watermarkBean) { float x, y, x1, y1, angle; final float OPACITY = 0.3f; PdfGState pdfGState = new PdfGState(); pdfGState.setFillOpacity(OPACITY); int pageWidth = (int) rectangle.getWidth(); int pageHeight = (int) rectangle.getHeight(); try { if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { pdfContentByte.beginText(); pdfContentByte.setGState(pdfGState); Color fillColor = watermarkBean.getFont().getColor() == null ? WatermarkConstants.DEFAULT_WATERMARK_COLOR : watermarkBean.getFont().getColor(); pdfContentByte.setColorFill(fillColor); if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_FOOTER)) { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getPositionFont().getSize()); if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) { pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(), (rectangle.getLeft(rectangle.getBorderWidthLeft()) + rectangle.getRight(rectangle.getBorderWidthRight())) / 2, rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) { pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(), rectangle.getRight(rectangle.getBorderWidthRight()), rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) { pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), rectangle.getLeft(rectangle.getBorderWidthLeft()), rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } } else if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_HEADER)) { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getPositionFont().getSize()); if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) { pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(), (rectangle.getLeft(rectangle.getBorderWidthLeft()) + rectangle.getRight(rectangle.getBorderWidthRight())) / 2, rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) { pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(), rectangle.getRight(rectangle.getBorderWidthRight()), rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) { pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), rectangle.getLeft(rectangle.getBorderWidthLeft()), rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } } else { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getFont().getSize()); int textWidth = (int) pdfContentByte.getEffectiveStringWidth(watermarkBean.getText(), false); int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight)); int pivotPoint = (diagonal - textWidth) / 2; angle = (float) Math.atan((float) pageHeight / pageWidth); x = (float) (pivotPoint * pageWidth) / diagonal; y = (float) (pivotPoint * pageHeight) / diagonal; x1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.sin(angle)); y1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.cos(angle)); pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), x + x1, y - y1, (float) Math.toDegrees(angle)); } pdfContentByte.endText(); } } catch (Exception exception) { LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception.getMessage()); } }
From source file:org.kuali.kra.printing.service.impl.WatermarkServiceImpl.java
License:Educational Community License
/** * /* www . j av a 2 s . co m*/ * This method for Decorating the PDF with watermark. * * @param pdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file * for decoration */ private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) { PdfReader pdfReader = watermarkPdfStamper.getReader(); int pageCount = pdfReader.getNumberOfPages(); int pdfPageNumber = 0; PdfContentByte pdfContents; Rectangle rectangle; while (pdfPageNumber < pageCount) { pdfPageNumber++; // pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber); rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber); pdfContents = watermarkPdfStamper.getUnderContent(pdfPageNumber); if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { decoratePdfWatermarkImage(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(), watermarkBean); } if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { decoratePdfWatermarkText(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(), watermarkBean); } } try { watermarkPdfStamper.close(); } catch (IOException decorateWatermark) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + decorateWatermark.getMessage()); } catch (DocumentException documentException) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + documentException.getMessage()); } }
From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java
License:Open Source License
@Override public boolean performFinish() { //create the document Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize()); Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); //rotate if we need landscape Document document = new Document(pageSize); try {// w ww. ja v a2s .com //Basic setup of the Document, and get instance of the iText Graphics2D // to pass along to uDig's standard "printing" code. String outputFile = page1.getDestinationDir() + System.getProperty("file.separator") + //$NON-NLS-1$ page1.getOutputFile(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); Graphics2D graphics = null; Template template = getTemplate(); int i = 0; int numPages = 1; do { //sets the active page template.setActivePage(i); PdfContentByte cb = writer.getDirectContent(); Page page = makePage(pageSize, document, template); graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight()); //instantiate a PrinterEngine (pass in the Page instance) PrintingEngine engine = new PrintingEngine(page); //make page format PageFormat pageFormat = new PageFormat(); pageFormat.setOrientation(PageFormat.PORTRAIT); java.awt.print.Paper awtPaper = new java.awt.print.Paper(); awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3); awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight()); pageFormat.setPaper(awtPaper); //run PrinterEngine's print function engine.print(graphics, pageFormat, 0); graphics.dispose(); document.newPage(); if (i == 0) { numPages = template.getNumPages(); } i++; } while (i < numPages); //cleanup document.close(); writer.close(); } catch (DocumentException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (PrinterException e) { e.printStackTrace(); } return true; }
From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java
License:Open Source License
protected Rectangle rotatePageIfNecessary(Rectangle suggestedPageSize) { //rotate the page if dimensions are given as portrait, but template prefers landscape if (suggestedPageSize.getHeight() > suggestedPageSize.getWidth() && page1.isLandscape()) { float temp = suggestedPageSize.getWidth(); float newWidth = suggestedPageSize.getHeight(); float newHeight = temp; return new Rectangle(suggestedPageSize.getHeight(), suggestedPageSize.getWidth()); }/*from w ww . ja v a 2s . c o m*/ return suggestedPageSize; }
From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java
License:Open Source License
/** * Creates a page based on the template selected in the wizard * **Note: this function may swap the width and height if the * template prefers different page orientation. * * @return a page// www . ja va 2 s. co m */ protected Page makePage(Rectangle pageSize, Document doc, Template template) { Map mapOnlyRasterLayers = null; Map mapNoRasterLayers = null; // **Note: the iText API doesn't render rasters at a high enough resolution if //they are written to the PDF via graphics2d. To work around this problem, I //create two copies of the map: one with only the raster layers, and one with //everything else. //The "everything else" map gets drawn by a graphics2d. The other layer must be //rasterized and inserted into the PDF via iText's API. //make one copy of the map with no raster layers mapNoRasterLayers = (Map) ApplicationGIS.copyMap(map); List<Layer> layersNoRasters = mapNoRasterLayers.getLayersInternal(); List<Layer> toRemove = new ArrayList<Layer>(); for (Layer layer : layersNoRasters) { for (IGeoResource resource : layer.getGeoResources()) { if (resource.canResolve(GridCoverageReader.class)) { toRemove.add(layer); } } } layersNoRasters.removeAll(toRemove); //adjust scale double currentViewportScaleDenom = map.getViewportModel().getScaleDenominator(); if (currentViewportScaleDenom == -1) throw new IllegalStateException("no scale denominator is available from the viewport model"); //$NON-NLS-1$ if (page1.getScaleOption() == PrintWizardPage1.CUSTOM_MAP_SCALE) { float customScale = page1.getCustomScale(); template.setMapScaleHint(customScale); } else if (page1.getScaleOption() == PrintWizardPage1.CURRENT_MAP_SCALE) { template.setMapScaleHint(currentViewportScaleDenom); } else if (page1.getScaleOption() == PrintWizardPage1.ZOOM_TO_SELECTION) { template.setZoomToSelectionHint(true); template.setMapScaleHint(currentViewportScaleDenom); } //3. make the page itself Page page = ModelFactory.eINSTANCE.createPage(); page.setSize(new Dimension((int) pageSize.getWidth(), (int) pageSize.getHeight())); //page name stuff not required, because this page will just get discarded MessageFormat formatter = new MessageFormat(Messages.CreatePageAction_newPageName, Locale.getDefault()); if (page.getName() == null || page.getName().length() == 0) { page.setName(formatter.format(new Object[] { mapNoRasterLayers.getName() })); } template.init(page, mapNoRasterLayers); if (page1.getRasterEnabled()) { //make another copy with only raster layers mapOnlyRasterLayers = (Map) ApplicationGIS.copyMap(map); List<Layer> layersOnlyRasters = mapOnlyRasterLayers.getLayersInternal(); List<Layer> toRemove2 = new ArrayList<Layer>(); for (Layer layer : layersOnlyRasters) { for (IGeoResource resource : layer.getGeoResources()) { if (!resource.canResolve(GridCoverageReader.class)) { toRemove2.add(layer); } } } layersOnlyRasters.removeAll(toRemove2); //set bounds to match the other map SetViewportBBoxCommand cmdBbox = new SetViewportBBoxCommand( mapNoRasterLayers.getViewportModel().getBounds()); mapOnlyRasterLayers.sendCommandSync(cmdBbox); if (layersNoRasters.size() > 0) { writeRasterLayersOnlyToDocument(mapOnlyRasterLayers, template.getMapBounds(), doc, page.getSize(), /*currentViewportScaleDenom*/mapNoRasterLayers.getViewportModel().getScaleDenominator()); } } //copy the boxes from the template into the page Iterator<Box> iter = template.iterator(); while (iter.hasNext()) { page.getBoxes().add(iter.next()); } return page; //TODO Throw some sort of exception if the page can't be created }
From source file:org.locationtech.udig.printing.ui.pdf.PrintWizard.java
License:Open Source License
@Override public boolean performFinish() { Template template = page1.getTemplateFactory().createTemplate(); boolean showRasters = page1.getRasterEnabled(); //adjust scale double currentViewportScaleDenom = map.getViewportModel().getScaleDenominator(); if (currentViewportScaleDenom == -1) throw new IllegalStateException("no scale denominator is available from the viewport model"); //$NON-NLS-1$ if (page1.getScaleOption() == PrintWizardPage1.CUSTOM_MAP_SCALE) { float customScale = page1.getCustomScale(); template.setMapScaleHint(customScale); } else if (page1.getScaleOption() == PrintWizardPage1.CURRENT_MAP_SCALE) { template.setMapScaleHint(currentViewportScaleDenom); } else if (page1.getScaleOption() == PrintWizardPage1.ZOOM_TO_SELECTION) { template.setZoomToSelectionHint(true); template.setMapScaleHint(currentViewportScaleDenom); }//from w ww . ja va 2 s .c om final PrinterJob printerJob = PrinterJob.getPrinterJob(); final PageFormat pageFormat = printerJob.defaultPage(); //setup the paper Paper paper = new Paper(); Rectangle pageSize = getITextPageSize(page1.getPageSize()); paper.setSize(pageSize.getWidth(), pageSize.getHeight()); //paper.setSize(11.7*72, 16.5*72); //double imageableWidth = paper.getWidth() - MARGIN*2; //double imageableHeight = paper.getHeight() - MARGIN*2; paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); pageFormat.setPaper(paper); if (page1.getTemplateFactory().createTemplate() .getPreferredOrientation() == Template.ORIENTATION_LANDSCAPE) { pageFormat.setOrientation(PageFormat.LANDSCAPE); } final String jobName = map.getName(); final TemplatePrintingEngine engine = new TemplatePrintingEngine(map, template, showRasters); printerJob.setPrintable(engine, pageFormat); Job job = new Job(Messages.PrintAction_jobTitle) { protected IStatus run(IProgressMonitor monitor) { if (printerJob.printDialog()) { try { printerJob.setJobName(jobName); printerJob.print(); } catch (Exception e) { e.printStackTrace(); } } return Status.OK_STATUS; } }; if (job.isSystem()) job.setSystem(false); job.schedule(); return true; }
From source file:org.mapfish.print.GetPageSizes.java
License:Open Source License
public static void main(String[] args) throws IllegalAccessException { Field[] fields = PageSize.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i];/* www. jav a 2 s . com*/ if (Modifier.isStatic(field.getModifiers())) { try { Rectangle val = (Rectangle) field.get(null); System.out.println(field.getName() + ": " + Math.round(val.getWidth()) + "x" + Math.round(val.getHeight())); } catch (Throwable ex) { System.out.println("Error with: " + field.getModifiers()); } } } }
From source file:org.mapfish.print.map.MapChunkDrawer.java
License:Open Source License
public void renderImpl(Rectangle rectangle, PdfContentByte dc) { final PJsonObject parent = context.getGlobalParams(); PJsonArray layers = parent.getJSONArray("layers"); String srs = parent.getString("srs"); if (!context.getConfig().isScalePresent(transformer.getScale())) { throw new InvalidJsonValueException(params, "scale", transformer.getScale()); }//from w w w .ja v a 2 s .c o m Transformer mainTransformer = null; if (!Double.isNaN(overviewMap)) { //manage the overview map mainTransformer = context.getLayout().getMainPage().getMap().createTransformer(context, params); transformer.zoom(mainTransformer, (float) (1.0 / overviewMap)); transformer.setRotation(0); //overview always north up! context.setStyleFactor((float) (transformer.getPaperW() / mainTransformer.getPaperW() / overviewMap)); layers = parent.optJSONArray("overviewLayers", layers); } transformer.setMapPos(rectangle.getLeft(), rectangle.getBottom()); if (rectangle.getWidth() < transformer.getPaperW() - 0.2) { throw new RuntimeException("The map width on the paper is wrong"); } if (rectangle.getHeight() < transformer.getPaperH() - 0.2) { throw new RuntimeException("The map height on the paper is wrong (" + rectangle.getHeight() + "!=" + transformer.getPaperH() + ")"); } //create the readers/renderers List<MapReader> readers = new ArrayList<MapReader>(layers.size()); for (int i = 0; i < layers.size(); ++i) { PJsonObject layer = layers.getJSONObject(i); if (mainTransformer == null || layer.optBool("overview", true)) { final String type = layer.getString("type"); MapReader.create(readers, type, context, layer); } } //check if we cannot merge a few queries for (int i = 1; i < readers.size();) { MapReader reader1 = readers.get(i - 1); MapReader reader2 = readers.get(i); if (reader1.testMerge(reader2)) { readers.remove(i); } else { ++i; } } //draw some background if (backgroundColor != null) { dc.saveState(); try { dc.setColorFill(backgroundColor); dc.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight()); dc.fill(); } finally { dc.restoreState(); } } //Do the rendering. // //Since we need to load tiles in parallel from the //servers, what follows is not trivial. We don't write directly to the PDF's //DirectContent, we always go through the ParallelMapTileLoader that will //make sure that everything is added to the PDF in the correct order. // //All uses of the DirectContent (dc) or the PDFWriter is forbiden outside //of renderOnPdf methods and when they are used, one must take a lock on //context.getPdfLock(). That is done for you when renderOnPdf is called, but not done //in the readTile method. That's why PDFUtils.getImage needs to do it when //creating the template. // //If you don't follow those rules, you risk to have random inconsistency //in your PDF files and/or infinite loops in iText. ParallelMapTileLoader parallelMapTileLoader = new ParallelMapTileLoader(context, dc); dc.saveState(); try { final PdfLayer mapLayer = new PdfLayer(name, context.getWriter()); transformer.setClipping(dc); //START of the parallel world !!!!!!!!!!!!!!!!!!!!!!!!!!! for (int i = 0; i < readers.size(); i++) { final MapReader reader = readers.get(i); //mark the starting of a new PDF layer parallelMapTileLoader.addTileToLoad(new MapTileTask.RenderOnly() { public void renderOnPdf(PdfContentByte dc) throws DocumentException { PdfLayer pdfLayer = new PdfLayer(reader.toString(), context.getWriter()); mapLayer.addChild(pdfLayer); dc.beginLayer(pdfLayer); } }); //render the layer reader.render(transformer, parallelMapTileLoader, srs, i == 0); //mark the end of the PDF layer parallelMapTileLoader.addTileToLoad(new MapTileTask.RenderOnly() { public void renderOnPdf(PdfContentByte dc) throws DocumentException { dc.endLayer(); } }); } } finally { //wait for all the tiles to be loaded parallelMapTileLoader.waitForCompletion(); //END of the parallel world !!!!!!!!!!!!!!!!!!!!!!!!!! dc.restoreState(); } if (mainTransformer != null) { //only for key maps: draw the real map extent drawMapExtent(dc, mainTransformer); context.setStyleFactor(1.0f); } }
From source file:org.mapfish.print.PDFCustomBlocks.java
License:Open Source License
private void addBackground(PdfWriter writer, Document document, PdfContentByte dc) { if (backgroundPdf != null) { try {/* w ww . ja va 2s .c om*/ PdfImportedPage page = backgroundPdfs.get(backgroundPdf); if (page == null) { PdfReader reader = new PdfReader(backgroundPdf); page = writer.getImportedPage(reader, 1); backgroundPdfs.put(backgroundPdf, page); } final Rectangle pageSize = document.getPageSize(); final boolean rotate = (page.getWidth() < page.getHeight()) ^ (pageSize.getWidth() < pageSize.getHeight()); if (rotate) { dc.addTemplate(page, 0, -1, 1, 0, 0, pageSize.getHeight()); } else { dc.addTemplate(page, 0, 0); } } catch (IOException e) { addError(e); } } }