Example usage for org.apache.pdfbox.pdmodel.common PDRectangle getHeight

List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getHeight

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.common PDRectangle getHeight.

Prototype

public float getHeight() 

Source Link

Document

This will get the height of this rectangle as calculated by upperRightY - lowerLeftY.

Usage

From source file:com.synopsys.integration.blackduck.report.pdf.RiskReportPdfWriter.java

License:Apache License

public File createPDFReportFile(final File outputDirectory, final ReportData report)
        throws RiskReportException {
    final IntegrationEscapeUtil escapeUtil = new IntegrationEscapeUtil();
    final String escapedProjectName = escapeUtil.escapeForUri(report.getProjectName());
    final String escapedProjectVersionName = escapeUtil.escapeForUri(report.getProjectVersion());
    final File pdfFile = new File(outputDirectory,
            escapedProjectName + "_" + escapedProjectVersionName + "_BlackDuck_RiskReport.pdf");
    if (pdfFile.exists()) {
        pdfFile.delete();//from  ww w  . j a  v  a 2 s.  c o m
    }
    final PDDocument document = new PDDocument();
    document.getDocumentInformation().setAuthor("Black Duck Software");
    document.getDocumentInformation().setCreator("Integrations");
    document.getDocumentInformation().setSubject("Hub Risk Report");

    try (PDFBoxManager pdfManager = new PDFBoxManager(pdfFile, document)) {
        this.pdfManager = pdfManager;
        final PDRectangle pageBox = pdfManager.currentPage.getMediaBox();
        final float pageWidth = pageBox.getWidth();
        final float pageHeight = pageBox.getHeight();

        final PDRectangle headerRectangle = writeHeader(pageWidth, pageHeight);
        final PDRectangle bottomOfProjectInfoRectangle = writeProjectInformation(pageWidth,
                headerRectangle.getLowerLeftY(), report);
        final PDRectangle bottomOfSummaryTableRectangle = writeSummaryTables(pageWidth,
                bottomOfProjectInfoRectangle.getLowerLeftY(), report);
        final PDRectangle bottomOfComponentTableRectangle = writeComponentTable(pageWidth,
                bottomOfSummaryTableRectangle.getLowerLeftY(), report);

        return pdfFile;
    } catch (final IOException | URISyntaxException e) {
        final String errorString = "Couldn't create the report: ";
        logger.trace(errorString + e.getMessage(), e);
        throw new RiskReportException(errorString + e.getMessage(), e);
    }
}

From source file:com.synopsys.integration.blackduck.service.model.pdf.RiskReportPdfWriter.java

License:Apache License

public File createPDFReportFile(final File outputDirectory, final ReportData report)
        throws RiskReportException {
    final IntegrationEscapeUtil escapeUtil = new IntegrationEscapeUtil();
    final String escapedProjectName = escapeUtil.escapeForUri(report.getProjectName());
    final String escapedProjectVersionName = escapeUtil.escapeForUri(report.getProjectVersion());
    final File pdfFile = new File(outputDirectory,
            escapedProjectName + "_" + escapedProjectVersionName + "_BlackDuck_RiskReport.pdf");
    if (pdfFile.exists()) {
        pdfFile.delete();/*from w  w w .j a v  a 2 s.c  om*/
    }
    final PDDocument document = new PDDocument();
    document.getDocumentInformation().setAuthor("Black Duck Software");
    document.getDocumentInformation().setCreator("Integrations");
    document.getDocumentInformation().setSubject("Black Duck Risk Report");

    try (PDFBoxManager pdfManager = new PDFBoxManager(pdfFile, document)) {
        this.pdfManager = pdfManager;
        final PDRectangle pageBox = pdfManager.currentPage.getMediaBox();
        final float pageWidth = pageBox.getWidth();
        final float pageHeight = pageBox.getHeight();

        final PDRectangle headerRectangle = writeHeader(pageWidth, pageHeight);
        final PDRectangle bottomOfProjectInfoRectangle = writeProjectInformation(pageWidth,
                headerRectangle.getLowerLeftY(), report);
        final PDRectangle bottomOfSummaryTableRectangle = writeSummaryTables(pageWidth,
                bottomOfProjectInfoRectangle.getLowerLeftY(), report);
        final PDRectangle bottomOfComponentTableRectangle = writeComponentTable(pageWidth,
                bottomOfSummaryTableRectangle.getLowerLeftY(), report);

        return pdfFile;
    } catch (final IOException | URISyntaxException e) {
        final String errorString = "Couldn't create the report: ";
        logger.trace(errorString + e.getMessage(), e);
        throw new RiskReportException(errorString + e.getMessage(), e);
    }
}

From source file:com.trollworks.gcs.pdfview.PdfPanel.java

License:Open Source License

private void markPageForLoading() {
    int numberOfPages = mPdf.getNumberOfPages();
    if (mPageIndex >= 0 && mPageIndex == numberOfPages) {
        mPageIndex = numberOfPages - 1;/*from  ww w  .j a  v a2s .  c o  m*/
    }
    if (mPageIndex >= 0 && mPageIndex < numberOfPages) {
        PDPage page = mPdf.getPage(mPageIndex);
        PDRectangle cropBox = page.getCropBox();
        float scale = SCALES[mScaleIndex] * Toolkit.getDefaultToolkit().getScreenResolution();
        mWidth = (int) Math.ceil(cropBox.getWidth() / 72 * scale);
        mHeight = (int) Math.ceil(cropBox.getHeight() / 72 * scale);
        mImg = null;
        mNeedLoad = true;
        Dimension size = new Dimension(mWidth, mHeight);
        UIUtilities.setOnlySize(this, size);
        setSize(size);
        repaint();
        mIgnorePageChange = true;
        mOwner.updateStatus(mPageIndex, numberOfPages, SCALES[mScaleIndex]);
        mIgnorePageChange = false;
    }
}

From source file:com.trollworks.gcs.pdfview.PdfRenderer.java

License:Open Source License

@Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
    text = text.toLowerCase();/*from w w w. j a  va 2  s .  c o m*/
    int index = text.indexOf(mTextToHighlight);
    if (index != -1) {
        PDPage currentPage = getCurrentPage();
        PDRectangle pageBoundingBox = currentPage.getBBox();
        AffineTransform flip = new AffineTransform();
        flip.translate(0, pageBoundingBox.getHeight());
        flip.scale(1, -1);
        PDRectangle mediaBox = currentPage.getMediaBox();
        float mediaHeight = mediaBox.getHeight();
        float mediaWidth = mediaBox.getWidth();
        int size = textPositions.size();
        while (index != -1) {
            int last = index + mTextToHighlight.length() - 1;
            for (int i = index; i <= last; i++) {
                TextPosition pos = textPositions.get(i);
                PDFont font = pos.getFont();
                BoundingBox bbox = font.getBoundingBox();
                Rectangle2D.Float rect = new Rectangle2D.Float(0, bbox.getLowerLeftY(),
                        font.getWidth(pos.getCharacterCodes()[0]), bbox.getHeight());
                AffineTransform at = pos.getTextMatrix().createAffineTransform();
                if (font instanceof PDType3Font) {
                    at.concatenate(font.getFontMatrix().createAffineTransform());
                } else {
                    at.scale(1 / 1000f, 1 / 1000f);
                }
                Shape shape = flip.createTransformedShape(at.createTransformedShape(rect));
                AffineTransform transform = mGC.getTransform();
                int rotation = currentPage.getRotation();
                if (rotation != 0) {
                    switch (rotation) {
                    case 90:
                        mGC.translate(mediaHeight, 0);
                        break;
                    case 270:
                        mGC.translate(0, mediaWidth);
                        break;
                    case 180:
                        mGC.translate(mediaWidth, mediaHeight);
                        break;
                    default:
                        break;
                    }
                    mGC.rotate(Math.toRadians(rotation));
                }
                mGC.fill(shape);
                if (rotation != 0) {
                    mGC.setTransform(transform);
                }
            }
            index = last < size - 1 ? text.indexOf(mTextToHighlight, last + 1) : -1;
        }
    }
}

From source file:com.vns.pdf.impl.PdfDocument.java

License:Apache License

private PdfDocument(String pdfFileName) throws IOException {
    this.pdfFileName = pdfFileName;
    setWorkingDir();/*from ww w  .  j  a v a  2  s  . co  m*/
    Path filePath = Paths.get(pdfFileName);
    PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class)
            .readAttributes();
    String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode()
            + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml";
    textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName);
    pdfTextStripper = new CustomPDFTextStripper();
    document = PDDocument.load(new File(pdfFileName));
    pdfRenderer = new PDFRenderer(document);

    if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) {
        pdfTextStripper.setSortByPosition(false);
        pdfTextStripper.setStartPage(0);
        pdfTextStripper.setEndPage(document.getNumberOfPages());

        this.doc = new Doc(new ArrayList<>(), new ArrayList<>());
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage pdPage = document.getPage(i);
            PDRectangle box = pdPage.getMediaBox();
            this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(),
                    (int) box.getHeight()));
        }

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        try {
            pdfTextStripper.writeText(document, dummy);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        parseBookmarksAnnotation();
        createTextAreaFile();
        //document.save(pdfFileName + ".pdf");
    } else {
        loadTextAreaFile();
    }
}

From source file:com.vns.pdf.impl.PdfDocument.java

License:Apache License

private List<Annotation> parseAnnotation(PDPage pdPage) throws IOException {
    List<Annotation> annotations = new ArrayList<>();
    for (PDAnnotation annt : pdPage.getAnnotations()) {
        if (annt instanceof PDAnnotationLink) {
            PDAnnotationLink link = (PDAnnotationLink) annt;
            PDRectangle rect = link.getRectangle();
            float x = rect.getLowerLeftX();
            float y = rect.getUpperRightY();
            float width = rect.getWidth();
            float height = rect.getHeight();
            int rotation = pdPage.getRotation();
            if (rotation == 0) {
                PDRectangle pageSize = pdPage.getMediaBox();
                y = pageSize.getHeight() - y;
            } else if (rotation == 90) {
                //do nothing
            }/*  w  ww .  j a  va 2 s. c  om*/

            ActionData actionData = parsePDAction(link.getAction());
            if (actionData == null) {
                actionData = parsePDDestination(link.getDestination());
            }
            if (actionData != null) {
                Annotation a = new Annotation(x, y, width, height, actionData.destX, actionData.destY,
                        actionData.destPage, actionData.destZoom);
                annotations.add(a);
            }
        }
    }
    return annotations;
}

From source file:com.yiyihealth.tools.test.DrawPrintTextLocations.java

License:Apache License

private void stripPage(int page) throws IOException {
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    image = pdfRenderer.renderImage(page, SCALE);

    PDPage pdPage = document.getPage(page);
    PDRectangle cropBox = pdPage.getCropBox();

    // flip y-axis
    flipAT = new AffineTransform();
    flipAT.translate(0, pdPage.getBBox().getHeight());
    flipAT.scale(1, -1);//from  w  w  w.ja  v a2 s.  c o m

    // page may be rotated
    rotateAT = new AffineTransform();
    int rotation = pdPage.getRotation();
    if (rotation != 0) {
        PDRectangle mediaBox = pdPage.getMediaBox();
        switch (rotation) {
        case 90:
            rotateAT.translate(mediaBox.getHeight(), 0);
            break;
        case 270:
            rotateAT.translate(0, mediaBox.getWidth());
            break;
        case 180:
            rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight());
            break;
        default:
            break;
        }
        rotateAT.rotate(Math.toRadians(rotation));
    }

    g2d = image.createGraphics();
    g2d.setStroke(new BasicStroke(0.1f));
    g2d.scale(SCALE, SCALE);

    setStartPage(page + 1);
    setEndPage(page + 1);

    Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
    writeText(document, dummy);

    // beads in green
    g2d.setStroke(new BasicStroke(0.4f));
    List<PDThreadBead> pageArticles = pdPage.getThreadBeads();
    for (PDThreadBead bead : pageArticles) {
        PDRectangle r = bead.getRectangle();
        GeneralPath p = r
                .transform(Matrix.getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY()));

        Shape s = flipAT.createTransformedShape(p);
        s = rotateAT.createTransformedShape(s);
        g2d.setColor(Color.green);
        g2d.draw(s);
    }

    g2d.dispose();

    String imageFilename = filename;
    int pt = imageFilename.lastIndexOf('.');
    imageFilename = imageFilename.substring(0, pt) + "-marked-" + (page + 1) + ".png";
    ImageIO.write(image, "png", new File(imageFilename));
}

From source file:controldeadministradores.Admin.java

public void crearPDF(String file, String body) throws Exception {
    String outputFileName = file + ".pdf";
    //        if (args.length > 0)
    //            outputFileName = args[0];

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);//from   www .jav  a  2s  . c  o m

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE;
    PDFont fontMono = PDType1Font.COURIER;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 0;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();
    cos.setFont(fontPlain, 14);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
    cos.drawString("Reporte de " + file);
    cos.endText();

    String[] txtLine = body.split("-");
    for (int k = 0; k < txtLine.length; k++) {
        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
        cos.drawString(txtLine[k]);
        cos.endText();
        cos.close();
    }

    // Make sure that the content stream is closed:

    // Save the results and ensure that the document is properly closed:
    document.save(outputFileName);
    document.close();
}

From source file:de.katho.kBorrow.controller.NewLendingController.java

License:Open Source License

/**
 * Erzeugt ein PDF-File mit allen relevanten Daten zur als Parameter bergebenen Lending-ID.
 * /*from   ww  w .  j ava  2  s .c  o  m*/
 * @param pLendingId   ID der Ausleihe, fr die ein PDF erzeugt werden soll.
 * @throws Exception   Wenn Probleme beim Erstellen der Datei auftreten.
 */
private void createPdfFile(int pLendingId) throws Exception {
    KLending lending = kLendingModel.getElement(pLendingId);
    KArticle article = kArticleModel.getElement(lending.getArticleId());
    KUser user = kUserModel.getElement(lending.getUserId());
    KLender lender = kLenderModel.getElement(lending.getLenderId());

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rect = page.getMediaBox();
    doc.addPage(page);

    PDFont fontNormal = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    String[] text = { "Artikel: ", "Verliehen von: ", "Ausgeliehen an: ", "Start der Ausleihe: ",
            "Voraussichtliche Rckgabe: " };
    String[] vars = { article.getName(), user.getName() + " " + user.getSurname(),
            lender.getName() + " " + lender.getSurname() + " (" + lender.getStudentnumber() + ")",
            lending.getStartDate(), lending.getExpectedEndDate() };
    try {
        File file = createRandomPdf();

        PDPageContentStream cos = new PDPageContentStream(doc, page);

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 100);
        cos.setFont(fontBold, 16);
        cos.drawString("Ausleihe #" + lending.getId());
        cos.endText();

        int i = 0;

        while (i < text.length) {
            cos.beginText();
            cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
            cos.setFont(fontBold, 12);
            cos.drawString(text[i]);
            cos.moveTextPositionByAmount(rect.getWidth() / 2 - 100, 0);
            cos.setFont(fontNormal, 12);
            cos.drawString(vars[i]);
            cos.endText();
            i++;
        }

        i = i + 2;
        cos.setLineWidth(1);
        cos.addLine(100, rect.getHeight() - 25 * (i + 2) - 100, 300, rect.getHeight() - 25 * (i + 2) - 100);
        cos.closeAndStroke();

        i++;

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
        cos.setFont(fontNormal, 12);
        cos.drawString("Unterschrift " + lender.getName() + " " + lender.getSurname());
        cos.endText();

        cos.close();
        doc.save(file);
        doc.close();

        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                desktop.open(file);
            }
        }
    } catch (IOException | COSVisitorException e) {
        throw new Exception("Problem bei der Erstellung der PDF-Datei.", e);
    }
}

From source file:de.mirkosertic.desktopsearch.pdfpreview.PDFPreviewGenerator.java

License:Open Source License

@Override
public synchronized Preview createPreviewFor(File aFile) {
    PDDocument theDocument = null;/*from www  .  j  a  va2 s. c  om*/
    try {
        theDocument = PDDocument.load(aFile);
        List<?> thePages = theDocument.getDocumentCatalog().getAllPages();
        if (thePages.isEmpty()) {
            return null;
        }
        PDPage theFirstPage = (PDPage) thePages.get(0);

        PDRectangle mBox = theFirstPage.findMediaBox();
        float theWidthPt = mBox.getWidth();
        float theHeightPt = mBox.getHeight();
        int theWidthPx = THUMB_WIDTH; // Math.round(widthPt * scaling);
        int theHeightPx = THUMB_HEIGHT; // Math.round(heightPt * scaling);
        float theScaling = THUMB_WIDTH / theWidthPt; // resolution / 72.0F;

        Dimension thePageDimension = new Dimension((int) theWidthPt, (int) theHeightPt);
        BufferedImage theImage = new BufferedImage(theWidthPx, theHeightPx, BufferedImage.TYPE_INT_RGB);
        Graphics2D theGraphics = (Graphics2D) theImage.getGraphics();
        theGraphics.setBackground(new Color(255, 255, 255, 0));

        theGraphics.clearRect(0, 0, theImage.getWidth(), theImage.getHeight());
        theGraphics.scale(theScaling, theScaling);
        PageDrawer theDrawer = new PageDrawer();
        theDrawer.drawPage(theGraphics, theFirstPage, thePageDimension);
        int rotation = theFirstPage.findRotation();
        if ((rotation == 90) || (rotation == 270)) {
            int w = theImage.getWidth();
            int h = theImage.getHeight();
            BufferedImage rotatedImg = new BufferedImage(w, h, theImage.getType());
            Graphics2D g = rotatedImg.createGraphics();
            g.rotate(Math.toRadians(rotation), w / 2, h / 2);
            g.drawImage(theImage, null, 0, 0);
        }
        theGraphics.dispose();
        return new Preview(ImageUtils.rescale(theImage, THUMB_WIDTH, THUMB_HEIGHT,
                ImageUtils.RescaleMethod.RESIZE_FIT_ONE_DIMENSION));
    } catch (Exception e) {
        LOGGER.error("Error creating preview for " + aFile, e);
        return null;
    } finally {
        try {
            // Always close the document
            theDocument.close();
        } catch (Exception e) {
        }
    }
}