Example usage for org.apache.pdfbox.pdmodel PDPage getMediaBox

List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage getMediaBox.

Prototype

public PDRectangle getMediaBox() 

Source Link

Document

A rectangle, expressed in default user space units, defining the boundaries of the physical medium on which the page is intended to be displayed or printed.

Usage

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  w ww .  ja v  a 2  s  .co 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:domain.mediator.PDFGeneration.java

public static void printTodayPDF(List<Logbook> logbookList, Driver driver, Load load,
        GPSLocation currentLocation) throws IOException {

    Table logbookTable = LogbookList.drawLogbookTable(logbookList);

    File saveFile = new File("todayTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);//  w ww. j  a  va2  s .  c o  m
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, logbookTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:domain.mediator.PDFGeneration.java

public static void printRecapPDF(List<Recap> recapList, Driver driver, Load load, GPSLocation currentLocation)
        throws IOException {

    Table recapTable = RecapList.drawRecapTable(recapList);

    File saveFile = new File("recapTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);/*from w  w  w  . ja va2s. co  m*/
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, recapTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:edu.uwm.jiaoduan.lab.ExtractTextByArea.java

License:Apache License

/**
 * This will print the documents text in a certain area.
 *
 * @param args The command line arguments.
 *
 * @throws Exception If there is an error parsing the document.
 */// ww  w  .  ja v  a 2 s .co  m
public static void main(String[] args) throws Exception {
    args = new String[] { "test.pdf" };
    if (args.length != 1) {
        usage();
    } else {
        PDDocument document = null;
        try {
            document = PDDocument.load(args[0]);
            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                } catch (InvalidPasswordException e) {
                    System.err.println("Error: Document is encrypted with a password.");
                    System.exit(1);
                }
            }
            PDFTextStripperByArea stripper = new PDFTextStripperByArea();
            stripper.setSortByPosition(true);
            //Rectangle rect = new Rectangle( 99,219,80,15 );
            //convert xfdf coordinate to rectangle

            Rectangle2D.Double rect = new Rectangle2D.Double();

            List allPages = document.getDocumentCatalog().getAllPages();
            PDPage firstPage = (PDPage) allPages.get(0);

            double pageHeight = firstPage.getMediaBox().getHeight();

            //125.824906,672.39502,390.577109,694.679017
            double[] coords = new double[] { 58.50615, 500.847504, 302.919073, 552.419312 };
            //rect.height = 694.679017 - 672.39502;
            rect.height = coords[3] - coords[1];
            //rect.width = 390.577109 - 125.824906;
            rect.width = coords[2] - coords[0];
            ;

            //rect.x = 125.824906;
            rect.x = coords[0];
            //rect.y = pageHeight -672.39502 - rect.height; 
            rect.y = pageHeight - coords[1] - rect.height;
            System.out.println(rect);

            stripper.addRegion("class1", rect);
            stripper.extractRegions(firstPage);

            System.out.println("Text in the area:" + rect);
            System.out.println(stripper.getTextForRegion("class1"));

        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:es.rickyepoderi.pdfimages.Converter.java

License:Open Source License

/**
 * Method that converts the images provides to pdf and writes to the target 
 * path specified./* ww w .j ava  2 s  . c o m*/
 *
 * @param output The file to write
 * @param bimages The buffered images to put in the pdf
 * @throws IOException Some error generating the PDF
 */
public void images2Pdf(File output, File... files) throws IOException {
    try (PDDocument pdDocument = new PDDocument()) {
        for (File file : files) {
            PDPage page = new PDPage();
            pdDocument.addPage(page);
            try (PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page,
                    PDPageContentStream.AppendMode.APPEND, true, true)) {
                BufferedImage bimage = ImageIO.read(file);
                PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bimage);
                Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()),
                        new Dimension((int) page.getMediaBox().getWidth(),
                                (int) page.getMediaBox().getHeight()));
                pageStream.drawImage(img, 0, 0, scaledDim.width, scaledDim.height);
            }
        }
        pdDocument.save(output);
    }
}

From source file:fr.aviz.hybridvis.utils.PDF.MultiScalePDFViewer.java

License:Open Source License

private BufferedImage printTitlesInImage(PDPage key, List<String> titles, Font itemFont) {

    int titlesInPage = titles.size();

    // assuming dimensions of PDF page for drawing
    int w = (int) key.getMediaBox().getWidth() - 200;
    int h = (int) key.getMediaBox().getHeight() - 100;
    int x = (int) key.getArtBox().getLowerLeftX() + 50;
    int y = (int) key.getArtBox().getLowerLeftY() + 50;

    // no idea why this is needed
    w *= 2;//from   w w w.j ava2s. c o m
    h *= 2;

    BufferedImage itemImage;
    if (!hybrid) {
        // calling createGraphics() to get the Graphics2D and setup for
        // drawing titles. Completely transparent
        itemImage = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    } else {
        itemImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    }

    Graphics2D g = itemImage.createGraphics();
    int currentTitle = titlesInPage;

    // background of title image transparent
    g.setColor(new Color(0f, 0f, 0f, opacity));
    for (String title : titles) {
        itemFont = scaleFontToFit(title, w - 100, g, itemFont);
        g.setFont(itemFont);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);

        g.drawString(title, (float) x,
                (float) (y + (titlesInPage - currentTitle + 1) * h / (titlesInPage + 1)));
        --currentTitle;
    }
    // releasing resources
    g.dispose();

    return itemImage;

}

From source file:fr.aviz.hybridvis.utils.PDF.MultiScalePDFViewer.java

License:Open Source License

private BufferedImage printTitlesAndCloudInImage(PDPage key, int pageNo, List<String> titles, Font itemFont) {

    // assuming dimensions of PDF page for drawing
    int w = (int) key.getMediaBox().getWidth() - 200;
    int h = (int) key.getMediaBox().getHeight() - 100;
    int x = (int) key.getArtBox().getLowerLeftX() + 50;
    int y = (int) key.getArtBox().getLowerLeftY() + 50;

    // no idea why this is needed
    w *= 2;//from  w w  w .  j ava 2  s.  c  o  m
    h *= 2;

    BufferedImage itemImage;
    if (!hybrid) {
        // calling createGraphics() to get the Graphics2D and setup for
        // drawing titles. Completely transparent
        itemImage = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    } else {
        itemImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    }

    int originalFont = itemFont.getSize();

    Graphics2D g = itemImage.createGraphics();

    // background of title image transparent
    g.setColor(new Color(1f, 1f, 1f, 0f));
    g.fillRect(0, 0, w, h);
    g.setColor(new Color(0f, 0f, 0f, opacity));

    if (titles != null) {
        int titlesInPage = titles.size();
        int currentTitle = titlesInPage;

        for (String title : titles) {
            itemFont = scaleFontToFit(title, w - 100, g, itemFont);
            g.setFont(itemFont);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);

            g.drawString(title, x, (float) ((titlesInPage - currentTitle + 1) * h * .5 / (titlesInPage + 1)));
            --currentTitle;
        }
    } else {
        System.out.println("PAGE NO TITLE");
    }

    String pageText;
    StringWriter pageTextWriter = new StringWriter();

    System.out.println("Printing text in p. " + pageNo);

    try {
        PDFts.setStartPage(pageNo);
        PDFts.setEndPage(pageNo);
        PDFts.writeText(document, pageTextWriter);
        pageText = pageTextWriter.toString();

        itemFont = itemFont.deriveFont(originalFont);
        g.setFont(itemFont);
        TagCloudImageGenerator tcig = new TagCloudImageGenerator(pageText, null, w, h / 2);

        int tw = tcig.getCloudImage().getWidth();
        int th = tcig.getCloudImage().getHeight();

        int y_drawing = h / 2 - 100;
        int x_drawing = 50;
        if (tw < w)
            x_drawing += .5 * (w - tw);

        if (titles == null)
            y_drawing = (int) (h / 4.0);

        g.drawImage(tcig.getCloudImage(), x_drawing, y_drawing, w, (h / 2), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // releasing resources
    g.dispose();

    return itemImage;
}

From source file:fr.aviz.hybridvis.utils.PDF.MultiScalePDFViewer.java

License:Open Source License

private BufferedImage printCloudInImage(PDPage key, int pageNo, List<String> titles, Font itemFont) {

    // assuming dimensions of PDF page for drawing
    int w = (int) key.getMediaBox().getWidth() - 200;
    int h = (int) key.getMediaBox().getHeight() - 100;
    int x = (int) key.getArtBox().getLowerLeftX() + 50;
    int y = (int) key.getArtBox().getLowerLeftY() + 50;

    // no idea why this is needed
    w *= 2;//  w w w.j  av  a  2 s.com
    h *= 2;

    BufferedImage itemImage;
    if (!hybrid) {
        // calling createGraphics() to get the Graphics2D and setup for
        // drawing titles. Completely transparent
        itemImage = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    } else {
        itemImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    }

    int originalFont = itemFont.getSize();

    Graphics2D g = itemImage.createGraphics();

    // background of title image transparent
    g.setColor(new Color(1f, 1f, 1f, 0f));
    g.fillRect(0, 0, w, h);
    g.setColor(new Color(0f, 0f, 0f, opacity));

    String pageText;
    StringWriter pageTextWriter = new StringWriter();

    System.out.println("Printing text in p. " + pageNo);

    try {
        PDFts.setStartPage(pageNo);
        PDFts.setEndPage(pageNo);
        PDFts.writeText(document, pageTextWriter);
        pageText = pageTextWriter.toString();

        itemFont = itemFont.deriveFont(originalFont);
        g.setFont(itemFont);
        TagCloudImageGenerator tcig = new TagCloudImageGenerator(pageText, null, w, 3 * h / 4);

        int tw = tcig.getCloudImage().getWidth();
        int th = tcig.getCloudImage().getHeight();

        int y_drawing = h / 4 - 100;
        int x_drawing = 50;
        if (tw < w)
            x_drawing += .5 * (w - tw);

        g.drawImage(tcig.getCloudImage(), x_drawing, y_drawing, w, 3 * h / 4, 0, 0,
                tcig.getCloudImage().getWidth(), tcig.getCloudImage().getHeight(), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // releasing resources
    g.dispose();

    return itemImage;
}

From source file:function.PrintImageLocations.java

License:Apache License

/**
 * This is used to handle an operation.//ww w.ja  v a 2 s .co m
 *
 * @param operator The operation to perform.
 * @param arguments The list of arguments.
 *
 * @throws IOException If there is an error processing the operation.
 */
protected void processOperator(PDFOperator operator, List arguments) throws IOException {
    String operation = operator.getOperation();
    if (INVOKE_OPERATOR.equals(operation)) {
        COSName objectName = (COSName) arguments.get(0);
        Map<String, PDXObject> xobjects = getResources().getXObjects();
        PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
        if (xobject instanceof PDXObjectImage) {
            PDXObjectImage image = (PDXObjectImage) xobject;
            PDPage page = getCurrentPage();
            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();
            double pageHeight = page.getMediaBox().getHeight();
            //System.out.println("*******************************************************************");
            System.out.println("Found image [" + objectName.getName() + "]");

            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctmNew.getYScale();
            float angle = (float) Math.acos(ctmNew.getValue(0, 0) / ctmNew.getXScale());
            if (ctmNew.getValue(0, 1) < 0 && ctmNew.getValue(1, 0) > 0) {
                angle = (-1) * angle;
            }
            ctmNew.setValue(2, 1, (float) (pageHeight - ctmNew.getYPosition() - Math.cos(angle) * yScaling));
            ctmNew.setValue(2, 0, (float) (ctmNew.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctmNew.setValue(0, 1, (-1) * ctmNew.getValue(0, 1));
            ctmNew.setValue(1, 0, (-1) * ctmNew.getValue(1, 0));
            AffineTransform ctmAT = ctmNew.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);

            float imageXScale = ctmNew.getXScale();
            float imageYScale = ctmNew.getYScale();
            System.out.println("position = " + ctmNew.getXPosition() + ", " + ctmNew.getYPosition());
            // size in pixel
            System.out.println("size = " + imageWidth + "px, " + imageHeight + "px");
            // size in page units
            System.out.println("size = " + imageXScale + ", " + imageYScale);
            // size in inches 
            imageXScale /= 72;
            imageYScale /= 72;
            System.out.println("size = " + imageXScale + "in, " + imageYScale + "in");
            // size in millimeter
            imageXScale *= 25.4;
            imageYScale *= 25.4;
            System.out.println("size = " + imageXScale + "mm, " + imageYScale + "mm");
            System.out.println();
            System.out.printf("dpi  = %.0f dpi (X), %.0f dpi (Y) %n",
                    image.getWidth() * 72 / ctmNew.getXScale(), image.getHeight() * 72 / ctmNew.getYScale());

        } else if (xobject instanceof PDXObjectForm) {
            // save the graphics state
            getGraphicsStack().push((PDGraphicsState) getGraphicsState().clone());
            PDPage page = getCurrentPage();

            PDXObjectForm form = (PDXObjectForm) xobject;
            COSStream invoke = (COSStream) form.getCOSObject();
            PDResources pdResources = form.getResources();
            if (pdResources == null) {
                pdResources = page.findResources();
            }
            // 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(getGraphicsState().getCurrentTransformationMatrix());
                getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
            }
            processSubStream(page, pdResources, invoke);

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

    } else {
        super.processOperator(operator, arguments);
    }
}

From source file:javaexample.RadialTextPdf.java

License:Open Source License

private void generatePage(PDDocument document) throws IOException {
    // Creates a new page.
    PDPage page = new PDPage(pageRect);
    document.addPage(page);// www .ja  v  a2 s  .co m

    // Gets boundings of the page.
    PDRectangle rect = page.getMediaBox();

    // Calculates the side of the square that fits into the page.
    float squareSide = Math.min(rect.getWidth(), rect.getHeight());

    // Calculates the center point of the page.
    float centerX = (rect.getLowerLeftX() + rect.getUpperRightX()) / 2;
    float centerY = (rect.getLowerLeftY() + rect.getUpperRightY()) / 2;

    PDPageContentStream cos = new PDPageContentStream(document, page);

    // Creates the font for the radial text.
    PDFont font = PDType1Font.HELVETICA_BOLD; // Standard font
    float fontSize = squareSide / 30;
    float fontAscent = font.getFontDescriptor().getAscent() / 1000 * fontSize;

    // Calculates key values for the drawings.
    float textX = squareSide / 3.4F; // x of the text.
    float textY = -fontAscent / 2; // y of the text (for vertical centering of text).
    float lineToX = textX * 0.97F; // x destination for the line.
    float lineWidth = squareSide / 900; // width of lines.

    // Moves the origin (0,0) of the axes to the center of the page.
    cos.concatenate2CTM(AffineTransform.getTranslateInstance(centerX, centerY));

    for (float degrees = 0; degrees < 360; degrees += 7.5) {
        double radians = degrees2Radians(degrees);

        // Creates a pure color with the hue based on the angle.
        Color textColor = Color.getHSBColor(degrees / 360.0F, 1, 1);

        // Saves the graphics state because the angle changes on each iteration.
        cos.saveGraphicsState();

        // Rotates the axes by the angle expressed in radians.
        cos.concatenate2CTM(AffineTransform.getRotateInstance(radians));

        // Draws a line from the center of the page.
        cos.setLineWidth(lineWidth);
        cos.moveTo(0, 0);
        cos.lineTo(lineToX, 0);
        cos.stroke();

        // Draws the radial text.
        cos.beginText();
        cos.setNonStrokingColor(textColor);
        cos.setFont(font, fontSize);
        cos.moveTextPositionByAmount(textX, textY);
        cos.drawString("PDF");
        cos.endText();

        // Restores the graphics state to remove rotation transformation.
        cos.restoreGraphicsState();
    }

    cos.close();
}