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

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

Introduction

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

Prototype

public PDPage(COSDictionary pageDictionary) 

Source Link

Document

Creates a new instance of PDPage for reading.

Usage

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to PDF option in the context menu.
 *//* w  ww  .  j  a  v a2 s.  c o  m*/
private void handleExportToPDF() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setSelectedExtensionFilter(
            new FileChooser.ExtensionFilter("Portable Document Format (PDF)", "pdf"));
    fileChooser.setTitle("Export to PDF");
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {

        try {

            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            PDDocument doc = new PDDocument();

            PDPage page = new PDPage(new PDRectangle((float) canvasPositionAndSize.totalWidth,
                    (float) canvasPositionAndSize.totalHeight));
            doc.addPage(page);

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            PDXObjectImage pdImage = new PDPixelMap(doc, image);
            contentStream.drawImage(pdImage, 0, 0);

            PDPageContentStream cos = new PDPageContentStream(doc, page);
            cos.drawXObject(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
            cos.close();

            doc.save(file);

        } catch (IOException | COSVisitorException ex) {
            Logger.getLogger(ChartViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
        (int)canvas.getHeight(), file);*/

        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
                (int)canvas.getHeight(), file);*/
    }
}

From source file:gamma.cvd.calculator.print.CVDPrint.java

private PDDocument createPdfDocument(CVDPatient patient) throws IOException {
    PDDocument document = new PDDocument();
    List<PDPage> pageList = new ArrayList<>();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    pageList.add(page1);// w ww  .  j  av  a2  s  .  co  m
    PDRectangle rect = pageList.get(0).getMediaBox();
    document.addPage(pageList.get(0));
    PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontCourier = PDType1Font.COURIER;
    PDFont fontCourierBold = PDType1Font.COURIER_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, pageList.get(0));
    line = 0;
    contentStream.beginText();
    contentStream.setFont(fontHelveticaBold, 18);
    contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace);
    contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName());
    contentStream.endText();

    contentStream.setFont(fontCourier, 12);
    writeLine("Patient no.:", String.valueOf(patient.getPatientId()), contentStream,
            rect.getHeight() - patientLineSpace);

    writeLine("First name:", patient.getFirstName(), contentStream, rect.getHeight() - patientLineSpace);

    writeLine("Last name:", patient.getLastName(), contentStream, rect.getHeight() - patientLineSpace);

    writeLine("Date of birth:", patient.getBirthdate().toString(), contentStream,
            rect.getHeight() - patientLineSpace);

    writeLine("Sex:", String.valueOf(patient.getSex()), contentStream, rect.getHeight() - patientLineSpace);
    int n = 0;
    for (CVDRiskData data : patient.getRiskData()) {
        if (n > 0 && n % 3 == 0) {
            contentStream.close();
            PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
            pageList.add(page);
            document.addPage(pageList.get(n / 3));
            contentStream = new PDPageContentStream(document, pageList.get(n / 3));
            line = 0;
            contentStream.beginText();
            contentStream.setFont(fontHelveticaBold, 18);
            contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace);
            contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName()
                    + ", page " + ((n / 3) + 1));
            contentStream.endText();
        }
        contentStream.beginText();
        contentStream.moveTextPositionByAmount(leftMargin,
                rect.getHeight() - testDataLineSpace - lineSpace * ++line);
        contentStream.endText();

        contentStream.setFont(fontCourierBold, 12);
        writeLine("Test ID:", String.valueOf(data.getTestId()), contentStream,
                rect.getHeight() - testDataLineSpace);

        contentStream.setFont(fontCourier, 12);
        writeLine("Test date:", data.getTestDate().toString(), contentStream,
                rect.getHeight() - testDataLineSpace);

        writeLine("Cholesterol type:", data.getCholesterolType(), contentStream,
                rect.getHeight() - testDataLineSpace);

        writeLine("Cholesterol mmol/L:", String.format("%.2f", data.getCholesterolMmolL()), contentStream,
                rect.getHeight() - testDataLineSpace);

        writeLine("HDL mmol/L:", String.format("%.2f", data.getHdlMmolL()), contentStream,
                rect.getHeight() - testDataLineSpace);

        writeLine("Diastolic blood pressure:", String.valueOf(data.getBloodPressureDiastolicMmHg()),
                contentStream, rect.getHeight() - testDataLineSpace);

        writeLine("Systolic blood pressure:", String.valueOf(data.getBloodPressureSystolicMmHg()),
                contentStream, rect.getHeight() - testDataLineSpace);

        if (data.isSmoker()) {
            writeLine("Patient is smoker:", "Yes", contentStream, rect.getHeight() - testDataLineSpace);
        } else {
            writeLine("Patient is smoker:", "No", contentStream, rect.getHeight() - testDataLineSpace);
        }

        if (data.isDiabetic()) {
            writeLine("Patient is diabetic:", "Yes", contentStream, rect.getHeight() - testDataLineSpace);
        } else {
            writeLine("Patient is diabetic:", "No", contentStream, rect.getHeight() - testDataLineSpace);
        }

        int score = data.calculateRiskScore();
        writeLine("Risk score:", String.valueOf(score), contentStream, rect.getHeight() - testDataLineSpace);

        int riskPercentage = data.getRiskPercentage(score);
        writeLine("Risk percentage:", new StringBuilder().append(riskPercentage).append(" %").toString(),
                contentStream, rect.getHeight() - testDataLineSpace);
        n++;
    }
    contentStream.close();
    return document;
}

From source file:info.informationsea.venn.graphics.VennDrawPDF.java

License:Open Source License

public static <T> void draw(VennFigure<T> vennFigure, PDDocument doc) throws IOException {
    // based on https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePDFA.java?revision=1703059&view=markup
    PDFont font = PDType0Font.load(doc, VennDrawPDF.class.getResourceAsStream("../fx/mplus-1p-regular.ttf"));

    Rectangle2D drawRect = vennFigure.drawRect(str -> stringBoundingBox(font, str, FONT_SIZE));
    PDRectangle pageSize = new PDRectangle((float) drawRect.getWidth() + MARGIN * 2,
            (float) drawRect.getHeight() + MARGIN * 2);
    PDPage page = new PDPage(pageSize);
    doc.addPage(page);//w  ww . j av  a  2  s.  c  om

    VennDrawPDF.draw(vennFigure, doc, page, font, pageSize);

    // PDF/A1b support
    /*
    // add XMP metadata
    XMPMetadata xmp = XMPMetadata.createXMPMetadata();
            
    try
    {
    DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
    dc.setTitle("Venn Diagram");
    dc.setSource("VennDraw "+ VersionResolver.getVersion());
    dc.setDescription("Venn Diagram");
            
    PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
    id.setPart(1);
    id.setConformance("B");
            
    XmpSerializer serializer = new XmpSerializer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    serializer.serialize(xmp, baos, true);
            
    PDMetadata metadata = new PDMetadata(doc);
    metadata.importXMPMetadata(baos.toByteArray());
    doc.getDocumentCatalog().setMetadata(metadata);
    } catch(BadFieldValueException|TransformerException  e) {
    throw new RuntimeException(e);
    }
            
    // sRGB output intent
    InputStream colorProfile = VennDrawPDF.class.getResourceAsStream(
        "sRGB Color Space Profile.icm");
    PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
    intent.setInfo("sRGB IEC61966-2.1");
    intent.setOutputCondition("sRGB IEC61966-2.1");
    intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
    intent.setRegistryName("http://www.color.org");
    doc.getDocumentCatalog().addOutputIntent(intent);
    */
}

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);//from  w  ww. j  a  v a2 s .  c o  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();
}

From source file:javaexample.StandardFontsDemoPdf.java

License:Open Source License

private void generatePage() throws IOException {
    // Creates a new page.
    page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/* www. jav  a 2s .com*/

    // Starting coordinates.
    x = mm2pt(15);
    y = mm2pt(276);

    cos = new PDPageContentStream(document, page);

    // Draws font name as page title.
    cos.setFont(PDType1Font.HELVETICA, 24);
    drawText(demoFont.getBaseFont(), x, y);

    y -= mm2pt(10);

    // Draws all font features.
    drawFontFeature("allCap", demoFontDescriptor.isAllCap());
    drawFontFeature("ascent", demoFontDescriptor.getAscent());
    drawFontFeature("averageWidth", demoFontDescriptor.getAverageWidth());
    drawFontFeature("capHeight", demoFontDescriptor.getCapHeight());
    drawFontFeature("charSet", demoFontDescriptor.getCharSet());
    drawFontFeature("descent", demoFontDescriptor.getDescent());
    drawFontFeature("fixedPitch", demoFontDescriptor.isFixedPitch());
    drawFontFeature("flags", demoFontDescriptor.getFlags());
    drawFontFeature("fontBoundingBox", demoFontDescriptor.getFontBoundingBox());
    drawFontFeature("fontFamily", demoFontDescriptor.getFontFamily());
    drawFontFeature("fontName", demoFontDescriptor.getFontName());
    drawFontFeature("fontStretch", demoFontDescriptor.getFontStretch());
    drawFontFeature("fontWeight", demoFontDescriptor.getFontWeight());
    drawFontFeature("forceBold", demoFontDescriptor.isForceBold());
    drawFontFeature("italic", demoFontDescriptor.isItalic());
    drawFontFeature("italicAngle", demoFontDescriptor.getItalicAngle());
    drawFontFeature("leading", demoFontDescriptor.getLeading());
    drawFontFeature("maxWidth", demoFontDescriptor.getMaxWidth());
    drawFontFeature("missingWidth", demoFontDescriptor.getMissingWidth());
    drawFontFeature("nonSymbolic", demoFontDescriptor.isNonSymbolic());
    drawFontFeature("script", demoFontDescriptor.isScript());
    drawFontFeature("serif", demoFontDescriptor.isSerif());
    drawFontFeature("smallCap", demoFontDescriptor.isSmallCap());
    drawFontFeature("stemH", demoFontDescriptor.getStemH());
    drawFontFeature("stemV", demoFontDescriptor.getStemV());
    drawFontFeature("symbolic", demoFontDescriptor.isSymbolic());
    drawFontFeature("xHeight", demoFontDescriptor.getXHeight());

    y -= mm2pt(5);
    cos.setNonStrokingColor(Color.BLACK);

    // Draws font demo string in different sizes.
    for (int i = 0; i < DEMO_FONT_SIZES.length; i++) {
        float demoFontSize = DEMO_FONT_SIZES[i];

        y -= demoFontSize + 9;

        cos.setFont(PDType1Font.HELVETICA, 8);
        drawText(demoFontSize + " pt", x, y); // Draws points size.

        cos.setFont(demoFont, demoFontSize);
        drawText(DEMO_STRING, x + mm2pt(12), y); // Draws demo string.
    }

    cos.close();
}

From source file:jgnash.report.pdf.Report.java

License:Open Source License

private PDPage createPage() {

    final PDPage page = new PDPage(
            new PDRectangle(0f, 0f, (float) getPageFormat().getWidth(), (float) getPageFormat().getHeight()));

    pdfDocument.addPage(page); // add the page to the document

    return page;// www.  j  ava2s . com
}

From source file:jlotoprint.PrintViewUIPanelController.java

public PDDocument generatePDF() throws Exception {

    PDDocument doc = null;/*w  ww  . jav a 2 s.  c om*/
    PDPage page = null;
    PDPageContentStream content = null;

    try {
        doc = new PDDocument();
        List<Group> pageList = importPageList(Template.getSourceFile(), Template.getModel());
        for (Parent node : pageList) {

            page = new PDPage(PDPage.PAGE_SIZE_A4);

            doc.addPage(page);

            PDRectangle mediaBox = page.getMediaBox();
            float pageWidth = mediaBox.getWidth();
            float pageHeight = mediaBox.getHeight();

            node.setTranslateX(0);
            node.setTranslateY(0);
            node.setScaleX(1);
            node.setScaleY(1);
            node.applyCss();
            node.layout();
            HashMap<String, Double> result = resizeProportional(node.getBoundsInParent().getWidth(),
                    node.getBoundsInParent().getHeight(), pageWidth, pageHeight, true);

            //get node image
            WritableImage nodeImage = node.snapshot(null, null);
            BufferedImage bufferedImage = SwingFXUtils.fromFXImage(nodeImage, null);

            //set page content
            content = new PDPageContentStream(doc, page);

            PDJpeg image = new PDJpeg(doc, bufferedImage, 1f);
            content.drawXObject(image, 0, 0, result.get("width").intValue(), result.get("height").intValue());

            content.close();
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (content != null) {
                content.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return doc;
}

From source file:jp.qpg.PDFPrinter.java

License:Apache License

/**
 * @return PDF content/*from ww  w  .j a v  a  2 s  . co  m*/
 */
protected PDPageContentStream getPage() {
    return page.orElseGet(Try.to(() -> {
        PDPage p = new PDPage(pageSize);
        logger.config("add PDPage: " + p.hashCode());
        getDocument().addPage(p);
        PDPageContentStream page = new PDPageContentStream(getDocument(), p);
        logger.config("create PDPageContentStream: " + page.hashCode());
        this.page = Optional.of(page);
        page.beginText();
        page.setFont(font, fontSize);
        page.newLineAtOffset(marginLeft, pageSize.getHeight() - fontSize - marginTop);
        currentX0 = currentX = marginLeft;
        currentY = marginTop;
        pageSetup.ifPresent(i -> i.accept(this));
        return page;
    }));
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void RotateButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButton1ActionPerformed
    PDDocument document = new PDDocument();
    InputStream in = null;//w ww  .  j a  va 2 s. c  om
    BufferedImage bimg = null;

    try {
        in = new FileInputStream((String) ImageFileField.getText());

        bimg = ImageIO.read(in);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Image could not be read.", "Image could not be read",
                JOptionPane.WARNING_MESSAGE);
    }
    float width = bimg.getWidth();
    float height = bimg.getHeight();
    PDPage page = new PDPage(new PDRectangle(width, height));
    document.addPage(page);
    PDImageXObject imgpdf;
    try {
        imgpdf = PDImageXObject.createFromFile((String) ImageFileField.getText(), document);

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            contentStream.drawImage(imgpdf, 0, 0);
        }

        in.close();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Image could not be converted.", "Proccess could not be finished",
                JOptionPane.WARNING_MESSAGE);
    }
    String destination = ImageDestinationField.getText() + "\\" + ImageNameField.getText() + ".pdf";
    PDDocumentInformation info = document.getDocumentInformation();
    info.setAuthor(ImageAuthorField.getText());
    File output = new File(destination);

    try {
        document.save(output);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem",
                JOptionPane.WARNING_MESSAGE);
    }
    try {
        document.close();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);//from w  ww.  j av a 2s  .c  o  m
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}