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

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

Introduction

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

Prototype

public float getUpperRightY() 

Source Link

Document

This will get the upper right y coordinate.

Usage

From source file:aplicacion.sistema.indexer.test.PDFTextStripperOrg.java

License:Apache License

/**
 * This will process a TextPosition object and add the
 * text to the list of characters on a page.  It takes care of
 * overlapping text./* w  ww .  jav  a2  s . c om*/
 *
 * @param text The text to process.
 */
protected void processTextPosition(TextPosition text) {
    boolean showCharacter = true;
    if (suppressDuplicateOverlappingText) {
        showCharacter = false;
        String textCharacter = text.getCharacter();
        float textX = text.getX();
        float textY = text.getY();
        List sameTextCharacters = (List) characterListMapping.get(textCharacter);
        if (sameTextCharacters == null) {
            sameTextCharacters = new ArrayList();
            characterListMapping.put(textCharacter, sameTextCharacters);
        }

        // RDD - Here we compute the value that represents the end of the rendered
        // text.  This value is used to determine whether subsequent text rendered
        // on the same line overwrites the current text.
        //
        // We subtract any positive padding to handle cases where extreme amounts
        // of padding are applied, then backed off (not sure why this is done, but there
        // are cases where the padding is on the order of 10x the character width, and
        // the TJ just backs up to compensate after each character).  Also, we subtract
        // an amount to allow for kerning (a percentage of the width of the last
        // character).
        //
        boolean suppressCharacter = false;
        float tolerance = (text.getWidth() / textCharacter.length()) / 3.0f;
        for (int i = 0; i < sameTextCharacters.size() && textCharacter != null; i++) {
            TextPosition character = (TextPosition) sameTextCharacters.get(i);
            String charCharacter = character.getCharacter();
            float charX = character.getX();
            float charY = character.getY();
            //only want to suppress

            if (charCharacter != null &&
            //charCharacter.equals( textCharacter ) &&
                    within(charX, textX, tolerance) && within(charY, textY, tolerance)) {
                suppressCharacter = true;
            }
        }
        if (!suppressCharacter) {
            sameTextCharacters.add(text);
            showCharacter = true;
        }
    }

    if (showCharacter) {
        //if we are showing the character then we need to determine which
        //article it belongs to.
        int foundArticleDivisionIndex = -1;
        int notFoundButFirstLeftAndAboveArticleDivisionIndex = -1;
        int notFoundButFirstLeftArticleDivisionIndex = -1;
        int notFoundButFirstAboveArticleDivisionIndex = -1;
        float x = text.getX();
        float y = text.getY();
        if (shouldSeparateByBeads) {
            for (int i = 0; i < pageArticles.size() && foundArticleDivisionIndex == -1; i++) {
                PDThreadBead bead = (PDThreadBead) pageArticles.get(i);
                if (bead != null) {
                    PDRectangle rect = bead.getRectangle();
                    if (rect.contains(x, y)) {
                        foundArticleDivisionIndex = i * 2 + 1;
                    } else if ((x < rect.getLowerLeftX() || y < rect.getUpperRightY())
                            && notFoundButFirstLeftAndAboveArticleDivisionIndex == -1) {
                        notFoundButFirstLeftAndAboveArticleDivisionIndex = i * 2;
                    } else if (x < rect.getLowerLeftX() && notFoundButFirstLeftArticleDivisionIndex == -1) {
                        notFoundButFirstLeftArticleDivisionIndex = i * 2;
                    } else if (y < rect.getUpperRightY() && notFoundButFirstAboveArticleDivisionIndex == -1) {
                        notFoundButFirstAboveArticleDivisionIndex = i * 2;
                    }
                } else {
                    foundArticleDivisionIndex = 0;
                }
            }
        } else {
            foundArticleDivisionIndex = 0;
        }
        int articleDivisionIndex = -1;
        if (foundArticleDivisionIndex != -1) {
            articleDivisionIndex = foundArticleDivisionIndex;
        } else if (notFoundButFirstLeftAndAboveArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstLeftAndAboveArticleDivisionIndex;
        } else if (notFoundButFirstLeftArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstLeftArticleDivisionIndex;
        } else if (notFoundButFirstAboveArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstAboveArticleDivisionIndex;
        } else {
            articleDivisionIndex = charactersByArticle.size() - 1;
        }

        List textList = (List) charactersByArticle.get(articleDivisionIndex);

        /* In the wild, some PDF encoded documents put diacritics (accents on
         * top of characters) into a separate Tj element.  When displaying them
         * graphically, the two chunks get overlayed.  With text output though,
         * we need to do the overlay. This code recombines the diacritic with
         * its associated character if the two are consecutive.
         */
        if (textList.isEmpty()) {
            textList.add(text);
        } else {
            /* test if we overlap the previous entry.  
             * Note that we are making an assumption that we need to only look back
             * one TextPosition to find what we are overlapping.  
             * This may not always be true. */
            TextPosition previousTextPosition = (TextPosition) textList.get(textList.size() - 1);
            if (text.isDiacritic() && previousTextPosition.contains(text)) {
                previousTextPosition.mergeDiacritic(text, normalize);
            }
            /* If the previous TextPosition was the diacritic, merge it into this
             * one and remove it from the list. */
            else if (previousTextPosition.isDiacritic() && text.contains(previousTextPosition)) {
                text.mergeDiacritic(previousTextPosition, normalize);
                textList.remove(textList.size() - 1);
                textList.add(text);
            } else {
                textList.add(text);
            }
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.pdfbox.positioning.Positioning.java

License:EUPL

private static PDRectangle rotateBox(PDRectangle cropBox, int rotation) {
    if (rotation != 0) {
        Point2D upSrc = new Point2D.Float();

        upSrc.setLocation(cropBox.getUpperRightX(), cropBox.getUpperRightY());

        Point2D llSrc = new Point2D.Float();
        llSrc.setLocation(cropBox.getLowerLeftX(), cropBox.getLowerLeftY());
        AffineTransform transform = new AffineTransform();
        transform.setToIdentity();/*from   w  ww  .ja va2s.  c om*/
        if (rotation % 360 != 0) {
            transform.setToRotation(Math.toRadians(rotation * -1), llSrc.getX(), llSrc.getY());
        }
        Point2D upDst = new Point2D.Float();
        transform.transform(upSrc, upDst);

        Point2D llDst = new Point2D.Float();
        transform.transform(llSrc, llDst);

        float y1 = (float) upDst.getY();
        float y2 = (float) llDst.getY();

        if (y1 > y2) {
            float t = y1;
            y1 = y2;
            y2 = t;
        }

        if (y1 < 0) {
            y2 = y2 + -1 * y1;
            y1 = 0;
        }

        float x1 = (float) upDst.getX();
        float x2 = (float) llDst.getX();

        if (x1 > x2) {
            float t = x1;
            x1 = x2;
            x2 = t;
        }

        if (x1 < 0) {
            x2 = x2 + -1 * x1;
            x1 = 0;
        }

        cropBox.setUpperRightX(x2);
        cropBox.setUpperRightY(y2);
        cropBox.setLowerLeftY(y1);
        cropBox.setLowerLeftX(x1);
    }
    return cropBox;
}

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/*from w w  w.  j ava2  s .  co m*/

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

From source file:chiliad.parser.pdf.extractor.vectorgraphics.operator.Invoke.java

License:Apache License

/**
 * process : Do : Paint the specified XObject (section 4.7).
 *
 * @param operator The operator that is being executed.
 * @param arguments List//from   ww  w.  j a va  2  s . co  m
 * @throws IOException If there is an error invoking the sub object.
 */
@Override
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    VectorGraphicsExtractor extractor = (VectorGraphicsExtractor) context;

    PDPage page = extractor.getPage();
    COSName objectName = (COSName) arguments.get(0);
    Map<String, PDXObject> xobjects = extractor.getResources().getXObjects();
    PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
    if (xobject == null) {
        LOG.warn("Can't find the XObject for '" + objectName.getName() + "'");
    } else if (xobject instanceof PDXObjectImage) {
        PDXObjectImage image = (PDXObjectImage) xobject;
        try {
            if (image.getImageMask()) {
                // set the current non stroking colorstate, so that it can
                // be used to create a stencil masked image
                image.setStencilColor(extractor.getGraphicsState().getNonStrokingColor());
            }
            BufferedImage awtImage = image.getRGBImage();
            if (awtImage == null) {
                LOG.warn("getRGBImage returned NULL");
                return;//TODO PKOCH
            }
            int imageWidth = awtImage.getWidth();
            int imageHeight = awtImage.getHeight();
            double pageHeight = extractor.getPageSize().getHeight();

            LOG.debug("imageWidth: " + imageWidth + "\t\timageHeight: " + imageHeight);

            Matrix ctm = extractor.getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctm.getYScale();
            float angle = (float) Math.acos(ctm.getValue(0, 0) / ctm.getXScale());
            if (ctm.getValue(0, 1) < 0 && ctm.getValue(1, 0) > 0) {
                angle = (-1) * angle;
            }
            ctm.setValue(2, 1, (float) (pageHeight - ctm.getYPosition() - Math.cos(angle) * yScaling));
            ctm.setValue(2, 0, (float) (ctm.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctm.setValue(0, 1, (-1) * ctm.getValue(0, 1));
            ctm.setValue(1, 0, (-1) * ctm.getValue(1, 0));
            AffineTransform ctmAT = ctm.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);
            extractor.drawImage(awtImage, ctmAT);
        } catch (Exception e) {
            LOG.error(e, e);
        }
    } else if (xobject instanceof PDXObjectForm) {
        // save the graphics state
        context.getGraphicsStack().push((PDGraphicsState) context.getGraphicsState().clone());

        PDXObjectForm form = (PDXObjectForm) xobject;
        COSStream formContentstream = form.getCOSStream();
        // find some optional resources, instead of using the current resources
        PDResources pdResources = form.getResources();
        // if there is an optional form matrix, we have to map the form space to the user space
        Matrix matrix = form.getMatrix();
        if (matrix != null) {
            Matrix xobjectCTM = matrix.multiply(context.getGraphicsState().getCurrentTransformationMatrix());
            context.getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
        }
        if (form.getBBox() != null) {
            PDGraphicsState graphicsState = context.getGraphicsState();
            PDRectangle bBox = form.getBBox();

            float x1 = bBox.getLowerLeftX();
            float y1 = bBox.getLowerLeftY();
            float x2 = bBox.getUpperRightX();
            float y2 = bBox.getUpperRightY();

            Point2D p0 = extractor.transformedPoint(x1, y1);
            Point2D p1 = extractor.transformedPoint(x2, y1);
            Point2D p2 = extractor.transformedPoint(x2, y2);
            Point2D p3 = extractor.transformedPoint(x1, y2);

            GeneralPath bboxPath = new GeneralPath();
            bboxPath.moveTo((float) p0.getX(), (float) p0.getY());
            bboxPath.lineTo((float) p1.getX(), (float) p1.getY());
            bboxPath.lineTo((float) p2.getX(), (float) p2.getY());
            bboxPath.lineTo((float) p3.getX(), (float) p3.getY());
            bboxPath.closePath();

            Area resultClippingArea = new Area(graphicsState.getCurrentClippingPath());
            Area newArea = new Area(bboxPath);
            resultClippingArea.intersect(newArea);

            graphicsState.setCurrentClippingPath(resultClippingArea);
        }
        getContext().processSubStream(page, pdResources, formContentstream);

        // restore the graphics state
        context.setGraphicsState((PDGraphicsState) context.getGraphicsStack().pop());
    }
}

From source file:com.devnexus.ting.web.controller.PdfUtils.java

License:Apache License

public PdfUtils(float margin, String title) throws IOException {
    this.margin = margin;
    doc = new PDDocument();
    baseFont = PDType0Font.load(doc, PdfUtils.class.getResourceAsStream("/fonts/Arial.ttf"));
    headerFont = PDType1Font.HELVETICA_BOLD;
    subHeaderFont = PDType1Font.HELVETICA_BOLD;
    devnexusLogo = PDDocument.load(PdfUtils.class.getResourceAsStream("/fonts/devnexus-logo.pdf"));

    this.currentPage = new PDPage();
    this.pages.add(currentPage);
    this.doc.addPage(currentPage);

    final PDRectangle mediabox = currentPage.getMediaBox();
    this.width = mediabox.getWidth() - 2 * margin;

    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    this.initialHeightCounter = startY;
    this.heightCounter = startY;

    LOGGER.info(String.format(/*w w  w .j  av a  2  s.c o m*/
            "Margin: %s, width: %s, startX: %s, "
                    + "startY: %s, heightCounter: %s, baseFontSize: %s, headerFontSize: %s",
            margin, width, startX, startY, heightCounter, baseFont, headerFont));

    contents = new PDPageContentStream(doc, currentPage);

    // Add Logo

    final LayerUtility layerUtility = new LayerUtility(doc);
    final PDFormXObject logo = layerUtility.importPageAsForm(devnexusLogo, 0);
    final AffineTransform affineTransform = AffineTransform.getTranslateInstance(100, startY - 50);
    affineTransform.scale(2d, 2d);
    layerUtility.appendFormAsLayer(currentPage, logo, affineTransform, "devnexus-logo");
    this.heightCounter -= 100;

    this.contents.beginText();

    this.contents.setFont(headerFont, headerFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    contents.newLineAtOffset(50, heightCounter);

    println(title);

    this.contents.setFont(baseFont, baseFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    println();

}

From source file:com.fileOperations.EmailBodyToPDF.java

/**
 * Places the text of the email into the PDF
 *
 * @param eml EmailBodyPDF/*from  ww  w  . ja v a 2s .  c om*/
 */
private static void createEmailBody(EmailBodyPDF eml) {
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    //Fonts used
    PDFont bodyTitleFont = PDType1Font.TIMES_BOLD;
    PDFont bodyFont = PDType1Font.TIMES_ROMAN;

    //Font Sizes
    float emailHeaderFontSize = 7;
    float leadingEmailHeader = 1.5f * emailHeaderFontSize;
    float bodyFontSize = 12;
    float leadingBody = 1.5f * bodyFontSize;

    try {
        //Create Document, Page, Margins.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);
        PDRectangle mediabox = page.getMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float textYlocation = margin;

        //Set Line Breaks
        List<String> sentDateContent = PDFBoxTools.setLineBreaks(eml.getSentDate(), width, emailHeaderFontSize,
                bodyFont);
        List<String> recievedDateContent = PDFBoxTools.setLineBreaks(eml.getReceiveDate(), width,
                emailHeaderFontSize, bodyFont);
        List<String> toContent = PDFBoxTools.setLineBreaks(eml.getTo(), width, emailHeaderFontSize, bodyFont);
        List<String> fromContent = PDFBoxTools.setLineBreaks(eml.getFrom(), width, emailHeaderFontSize,
                bodyFont);
        List<String> ccContent = PDFBoxTools.setLineBreaks(eml.getCc(), width, emailHeaderFontSize, bodyFont);
        List<String> bccContent = PDFBoxTools.setLineBreaks(eml.getBcc(), width, emailHeaderFontSize, bodyFont);
        List<String> attachmentContent = PDFBoxTools.setLineBreaks(eml.getAttachments(), width,
                emailHeaderFontSize, bodyFont);
        List<String> subjectContent = PDFBoxTools.setLineBreaks(eml.getSubject(), width, bodyFontSize,
                bodyFont);
        List<String> bodyContent = PDFBoxTools.setLineBreaks(eml.getBody(), width, bodyFontSize, bodyFont);

        //Set Email Header
        contentStream.beginText();
        contentStream.setFont(bodyFont, emailHeaderFontSize);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(startX, startY);

        //Set Date Sent
        if (!"".equals(eml.getSentDate())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Sent: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : sentDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Date Received
        if (!"".equals(eml.getReceiveDate().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Date Received: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : recievedDateContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingBody;
            }
        }
        contentStream.newLineAtOffset(0, -leadingBody);

        //Set From
        if (!"".equals(eml.getFrom().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("From: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : fromContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set To
        if (!"".equals(eml.getTo().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("To: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : toContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set CC
        if (!"".equals(eml.getCc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("CC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : ccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set BCC
        if (!"".equals(eml.getBcc().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("BCC: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : bccContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set AttachmentList
        if (!"".equals(eml.getAttachments().trim())) {
            contentStream.setFont(bodyTitleFont, emailHeaderFontSize);
            contentStream.showText("Attachments: ");
            contentStream.setFont(bodyFont, emailHeaderFontSize);
            contentStream.newLineAtOffset(0, -leadingEmailHeader);
            textYlocation += leadingEmailHeader;
            for (String line : attachmentContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingEmailHeader);
                textYlocation += leadingEmailHeader;
            }
        }

        //Set Subject
        if (!"".equals(eml.getSubject().trim())) {
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Subject: ");
            contentStream.newLineAtOffset(0, -leadingBody);
            textYlocation += leadingBody;
            contentStream.setFont(bodyFont, bodyFontSize);
            for (String line : subjectContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, emailHeaderFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }
                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
                textYlocation += leadingBody;
            }
        }
        if (!"".equals(eml.getBody().trim())) {
            // Set Email Body
            contentStream.newLineAtOffset(0, -leadingBody);
            contentStream.setFont(bodyTitleFont, bodyFontSize);
            contentStream.showText("Message: ");
            contentStream.setFont(bodyFont, bodyFontSize);
            contentStream.newLineAtOffset(0, -leadingBody);
            for (String line : bodyContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, bodyFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                textYlocation += leadingBody;

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
            }
            contentStream.endText();

        }
        contentStream.close();
        doc.save(eml.getFilePath() + eml.getFileName());
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.fileOperations.TXTtoPDF.java

/**
 * Takes the text from the string and insert it into the PDF file
 *
 * @param pdfFile String (path + filename)
 * @param text String (text from document)
 *//*from  w  w w  .  jav a 2 s .  com*/
private static void makePDF(String pdfFile, String text) {
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    //Fonts used
    PDFont bodyFont = PDType1Font.TIMES_ROMAN;

    //Font Sizes
    float bodyFontSize = 12;
    float leadingBody = 1.5f * bodyFontSize;

    try {
        //Create Document, Page, Margins.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false);
        PDRectangle mediabox = page.getMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float textYlocation = margin;

        //Set Line Breaks
        text = text.replaceAll("[\\p{C}\\p{Z}]", System.getProperty("line.separator")); //strip ZERO WIDTH SPACE
        List<String> textContent = PDFBoxTools.setLineBreaks(text, width, bodyFontSize, bodyFont);

        contentStream.beginText();
        contentStream.setFont(bodyFont, bodyFontSize);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(startX, startY);

        if (!"".equals(text)) {
            for (String line : textContent) {
                if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) {
                    contentStream.endText();
                    contentStream.close();
                    textYlocation = 0;

                    page = new PDPage();
                    doc.addPage(page);
                    contentStream = new PDPageContentStream(doc, page, true, true, false);

                    contentStream.beginText();
                    contentStream.setFont(bodyFont, bodyFontSize);
                    contentStream.setNonStrokingColor(Color.BLACK);
                    contentStream.newLineAtOffset(startX, startY);
                }

                textYlocation += leadingBody;

                contentStream.showText(line);
                contentStream.newLineAtOffset(0, -leadingBody);
            }
            contentStream.endText();

        }
        contentStream.close();
        doc.save(pdfFile);
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.formkiq.core.service.conversion.PdfToPngFormatConverter.java

License:Apache License

/**
 * Find {@link PDSignatureField} on the Image.
 * @param doc {@link PDDocument}//from   w w w  . j  a va2 s. c o  m
 * @param result {@link ConversionResult}
 * @return {@link List} of {@link ConversionField}
 * @throws IOException IOException
 */
private List<ConversionField> findSigningButtons(final PDDocument doc, final ConversionResult result)
        throws IOException {

    List<ConversionField> fields = new ArrayList<>();
    List<PDSignatureField> sigs = doc.getSignatureFields();

    for (PDSignatureField s : sigs) {

        PDRectangle rect = PDRectangleUtil.calculateWidget(s.getWidgets());
        PDAnnotationWidget widget = s.getWidgets().get(0);
        PDPage page = widget.getPage();

        int pageNumber = doc.getPages().indexOf(page);
        float imagePageSize = result.getDataheight() / doc.getNumberOfPages();
        float x = rect.getLowerLeftX();
        float y = (imagePageSize - rect.getUpperRightY()) + (imagePageSize * pageNumber);

        ConversionField f = new ConversionField();
        f.setDocumentfieldname(s.getFullyQualifiedName());
        f.setX(x);
        f.setY(y);
        f.setHeight(rect.getHeight());
        fields.add(f);
    }

    return fields;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfTextFieldHorizontalGroupComparator.java

License:Apache License

@Override
public int compare(final PdfTextField t1, final PdfTextField t2) {

    PDRectangle r1 = t1.getRectangle();
    PDRectangle r2 = t2.getRectangle();/*from   w  w w  .ja va  2  s .c o m*/

    int r = Float.compare(t1.getFontSize(), t2.getFontSize());

    if (r == 0) {
        int v1 = Math.round(r1.getUpperRightY());
        int v2 = Math.round(r2.getUpperRightY());
        r = Integer.compare(v2, v1);
    }

    if (r == 0) {

        int d0 = round(abs(r1.getUpperRightX() - r2.getLowerLeftX()));
        int d1 = round(abs(r2.getUpperRightX() - r1.getLowerLeftX()));

        r = d0 < t1.getFontSize() || d1 < t1.getFontSize() ? 0 : -1;
    }

    return r;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfTextFieldTextGroupComparator.java

License:Apache License

@Override
public int compare(final PdfTextField o1, final PdfTextField o2) {

    PDRectangle r1 = o1.getRectangle();/*  w ww .  ja v a 2s . c  o m*/
    PDRectangle r2 = o2.getRectangle();

    int v1 = Math.round(r1.getLowerLeftX());
    int v2 = Math.round(r2.getLowerLeftX());
    int r = Integer.compare(v1, v2);

    if (r == 0) {
        r = Float.compare(o1.getFontSize(), o2.getFontSize());
    }

    if (r == 0) {
        r = o1.getFontName().compareTo(o2.getFontName());
    }

    // check if lower position if within Y location + font size away from
    // text above
    if (r == 0) {
        float diff0 = Math.abs(r1.getLowerLeftY() - r2.getUpperRightY());
        float diff1 = Math.abs(r1.getUpperRightY() - r2.getLowerLeftY());
        r = diff0 <= o2.getFontSize() || diff1 <= o2.getFontSize() ? 0 : -1;
    }

    return r;
}