Example usage for com.lowagie.text Rectangle getWidth

List of usage examples for com.lowagie.text Rectangle getWidth

Introduction

In this page you can find the example usage for com.lowagie.text Rectangle getWidth.

Prototype

public float getWidth() 

Source Link

Document

Returns the width of the rectangle.

Usage

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  w w  . ja  va2 s.  co 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/*from  ww  w.ja va 2s .  com*/
 */
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);
    }// w w w  .  j a v a 2  s.  c o  m

    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.config.layout.HeaderFooter.java

License:Open Source License

public void render(final Rectangle rectangle, PdfContentByte dc, PJsonObject params, RenderingContext context) {
    try {/*  w w  w . j a va  2s  .c o  m*/
        final PdfPTable table = PDFUtils.buildTable(items, params, context,
                1/*multiple items are arranged by lines*/, null);
        if (table != null) {
            table.setTotalWidth(rectangle.getWidth());
            table.writeSelectedRows(0, -1, rectangle.getLeft(), rectangle.getTop(), dc);
        }
    } catch (DocumentException e) {
        context.addError(e);
    }
}

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];/*from  w  w w .  j a  va  2s  .  c o  m*/
        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  va2s.c om

    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 {/*from w  w  w  .j a v  a 2 s  .c  o  m*/
            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);
        }
    }
}

From source file:org.nuxeo.dam.pdf.export.PDFCreator.java

License:Open Source License

public boolean createPDF(String title, OutputStream out) throws ClientException {
    try {/*from  w ww. j  a v a 2  s  . c o m*/
        Document document = new Document();
        PdfWriter.getInstance(document, out);

        document.addTitle(title);
        document.addAuthor(Functions.principalFullName(currentUser));
        document.addCreator(Functions.principalFullName(currentUser));

        document.open();

        document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n"));
        Font titleFont = new Font(Font.HELVETICA, 36, Font.BOLD);
        Paragraph titleParagraph = new Paragraph(title, titleFont);
        titleParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(titleParagraph);
        Font authorFont = new Font(Font.HELVETICA, 20);
        Paragraph authorParagraph = new Paragraph("By " + Functions.principalFullName(currentUser), authorFont);
        authorParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(authorParagraph);

        document.newPage();

        boolean foundOnePicture = false;
        for (DocumentModel doc : docs) {
            if (!doc.hasSchema(PICTURE_SCHEMA)) {
                continue;
            }
            foundOnePicture = true;

            PictureResourceAdapter picture = doc.getAdapter(PictureResourceAdapter.class);
            Blob blob = picture.getPictureFromTitle(ORIGINAL_JPEG_VIEW);
            Rectangle pageSize = document.getPageSize();
            if (blob != null) {
                Paragraph imageTitle = new Paragraph(doc.getTitle(), font);
                imageTitle.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(imageTitle);

                Image image = Image.getInstance(blob.getByteArray());
                image.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight() - 100);
                image.setAlignment(Image.MIDDLE);
                Paragraph imageParagraph = new Paragraph();
                imageParagraph.add(image);
                imageParagraph.setAlignment(Paragraph.ALIGN_MIDDLE);
                document.add(imageParagraph);

                document.newPage();
            }
        }
        if (foundOnePicture) {
            document.close();
            return true;
        }
    } catch (Exception e) {
        throw ClientException.wrap(e);
    }
    return false;
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

/**
 * @since 5.8 Provides the position rectangle for the next certificate. An assumption is made that all previous
 *        certificates in a given PDF were placed using the same technique and settings. New certificates are added
 *        depending of signature layout contributed.
 *///from w w w. j  a va  2s. c om
protected Rectangle getNextCertificatePosition(PdfReader pdfReader, List<X509Certificate> pdfCertificates)
        throws SignException {
    int numberOfSignatures = pdfCertificates.size();

    Rectangle pageSize = pdfReader.getPageSize(PAGE_TO_SIGN);

    // PDF size
    float width = pageSize.getWidth();
    float height = pageSize.getHeight();

    // Signature size
    float rectangleWidth = width / getSignatureLayout().getColumns();
    float rectangeHeight = height / getSignatureLayout().getLines();

    // Signature location
    int column = numberOfSignatures % getSignatureLayout().getColumns() + getSignatureLayout().getStartColumn();
    int line = numberOfSignatures / getSignatureLayout().getColumns() + getSignatureLayout().getStartLine();
    if (column > getSignatureLayout().getColumns()) {
        column = column % getSignatureLayout().getColumns();
        line++;
    }

    // Skip rectangle display If number of signatures exceed free locations
    // on pdf layout
    if (line > getSignatureLayout().getLines()) {
        return new Rectangle(0, 0, 0, 0);
    }

    // make smaller by page margin
    float topRightX = rectangleWidth * column;
    float bottomLeftY = height - rectangeHeight * line;
    float bottomLeftX = topRightX - SIGNATURE_FIELD_WIDTH;
    float topRightY = bottomLeftY + SIGNATURE_FIELD_HEIGHT;

    // verify current position coordinates in case they were
    // misconfigured
    validatePageBounds(pdfReader, 1, bottomLeftX, true);
    validatePageBounds(pdfReader, 1, bottomLeftY, false);
    validatePageBounds(pdfReader, 1, topRightX, true);
    validatePageBounds(pdfReader, 1, topRightY, false);

    Rectangle positionRectangle = new Rectangle(bottomLeftX, bottomLeftY, topRightX, topRightY);

    return positionRectangle;
}

From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java

License:Open Source License

private void init() throws FileNotFoundException {

    // we create a reader for a certain document
    PdfReader reader = null;//from   www  .j  a v  a  2s  .  c o  m
    PdfWriter writer = null;
    try {
        reader = new PdfReader(getStreamStatic(this.fileNameIn));

        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // we retrieve the size of the first page
        Rectangle psize = reader.getPageSize(1);

        psize.setRight(psize.getRight() - this.templateOffsetX);
        psize.setTop(psize.getTop() - this.templateOffsetY);

        this.width = (int) psize.getWidth();
        float height = psize.getHeight();

        // step 1: creation of a document-object
        int MARGIN = 32;
        this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN);
        // step 2: we create a writer that listens to the document
        if (!this.directoryOut.exists()) {
            this.directoryOut.mkdirs();
        }
        System.err.println("Directory out " + this.directoryOut.getAbsolutePath());
        File f = new File(this.directoryOut, this.fileNameOut);
        if (f.exists()) {
            f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut));
            f = new File(this.directoryOut, this.fileNameOut);
        }

        System.err.println("Creation du fichier " + f.getAbsolutePath());

        writer = PdfWriter.getInstance(this.document, new FileOutputStream(f));

        this.document.open();
        // step 4: we add content
        this.cb = writer.getDirectContent();

        System.out.println("There are " + n + " pages in the document.");

        this.document.newPage();

        PdfImportedPage page1 = writer.getImportedPage(reader, 1);

        this.cb.addTemplate(page1, -this.templateOffsetX, -this.templateOffsetY);

        this.bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        this.bfb = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED);

    } catch (FileNotFoundException fE) {
        throw fE;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}