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

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

Introduction

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

Prototype

public PDPageContentStream(PDDocument doc, PDAppearanceStream appearance) throws IOException 

Source Link

Document

Create a new appearance stream.

Usage

From source file:de.schneefisch.fruas.transactions.DeliveryNotePDFCreator.java

public void createPDF() {

    String filename = "Lieferschein-" + deliveryNote.getId() + ".pdf";

    try {//from  w  w  w .j av  a  2 s .  c o  m
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(70, 750);
        content.showText("Schneefisch GmbH");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 13);
        content.newLineAtOffset(70, 725);
        content.showText("Nibelungenplatz 1");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 14);
        content.newLineAtOffset(70, 700);
        content.showText("D-60318 Frankfurt am Main");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 640);
        content.showText(fiCustomer.getName());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 620);
        content.showText("Wareneingang");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 600);
        content.showText(location.getStreet() + " " + location.getHouseNumber());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 580);
        content.showText(location.getPostalCode() + " " + location.getCity());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(300, 540);
        content.showText("Lieferschein " + deliveryNote.getId() + " fuer KN " + fiCustomer.getId());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(75, 500);
        content.showText("POS");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(120, 500);
        content.showText("Bezeichnung");
        content.endText();

        int count = 1;
        float yoffset = 460;
        for (DeliveryNotePosition dnp : deliveryNotePositions) {
            LicenseDAO licDAO = new LicenseDAO();
            License license = licDAO.selectLicenseById(dnp.getLicenseId());
            ProductDAO pDAO = new ProductDAO();
            Product product = pDAO.searchProductById(license.getProductId());

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(75, yoffset);
            content.showText(Integer.toString(count));
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(120, yoffset);
            content.showText(product.getName());
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(120, yoffset - 20);
            content.showText("Lizenz: " + license.getId() + " von " + license.getSoldDate() + " bis "
                    + license.getEndDate() + ".");
            content.endText();
            if (license.getMaintenanceId() == 0) {
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 12);
                content.newLineAtOffset(120, yoffset - 40);
                content.showText("Ohne Maintenance-Vertrag.");
                content.endText();
            } else {
                MaintenanceDAO mDAO = new MaintenanceDAO();
                Maintenance maintenance = mDAO.searchMaintenanceById(license.getMaintenanceId());
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 12);
                content.newLineAtOffset(120, yoffset - 40);
                content.showText("Mit " + maintenance.getInfo() + " als Maintenance-Vertrag.");
                content.endText();
            }
            count++;
            yoffset -= 100;
        }

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Rechnungslegung erfolgt separat.");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Das Produkt bleibt bis zur vollstndigen Bezahlung unser Eigentum.");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Mit freundlichen Gruessen");
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Schneefisch GmbH");
        content.endText();
        content.close();

        doc.save(filename);
        doc.close();
        System.out.println(filename + " erstellt in: " + System.getProperty("user.dir"));
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

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);//from w  ww. ja va 2  s .com
    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  ww . j  a v  a2s  .  com
    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:gov.samhsa.c2s.common.pdfbox.enhance.HexPdf.java

License:Apache License

/**
 * Close the current page (if any), and open a new one. Cursor position is
 * reset to top-left corner of writable area (within margins)
 *
 * @see #closePage()/*from  w  w  w.ja v a 2s .  co m*/
 */
public void newPage() {

    numPages++;
    if (currentPage != null) {
        closePage();
    }

    currentPage = new PDPage();
    float x1 = this.pageSize.getLowerLeftX();
    float y1 = this.pageSize.getLowerLeftY();
    float x2 = this.pageSize.getUpperRightX();
    float y2 = this.pageSize.getUpperRightY();
    float w = this.pageSize.getWidth();
    float h = this.pageSize.getHeight();
    if (orientation == HexPdf.PORTRAIT) {
        pageWidth = w;
        pageHeight = h;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(x1, y1, x2, y2)));
    } else {
        pageWidth = h;
        pageHeight = w;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(y1, x1, y2, x2)));
    }

    setDimensions();
    cursorX = contentStartX;
    cursorY = contentStartY;
    try {
        cs = new PDPageContentStream(this, currentPage);
        cs.setFont(font, fontSize);
    } catch (IOException ex) {
        Logger.getLogger(HexPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeSummaryReport(MainController mc) {

    mc.selectStep(6);/*w  w  w .j a  v  a 2 s  .  c  o m*/
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                boolean exportSuccess = true;
                try {
                    PDDocument doc = new PDDocument();
                    for (int factSheetIdx = 1; factSheetIdx <= 8; factSheetIdx++) {

                        Node n = mc.goToFactSheet(factSheetIdx, true);
                        MainController.getStage().show();
                        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();

                        PDPage page = new PDPage();
                        doc.addPage(page);

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

                        double prefHeight = wi.getHeight();
                        double prefWidth = wi.getWidth();
                        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);

                        PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
                        int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
                        int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
                        int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
                        drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
                        content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth,
                                drawHeight);
                        content.fillAndStroke();
                        content.close();
                    }
                    drawReportHeaderFooter(doc, mc.getProject(), true);
                    doc.save(saveFile);
                    doc.close();
                } catch (IOException ie) {
                    System.out.println("ERROR");
                    exportSuccess = false;
                }
                if (exportSuccess) {
                    Alert al = new Alert(Alert.AlertType.CONFIRMATION);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export successful");
                    al.showAndWait();
                } else {
                    Alert al = new Alert(Alert.AlertType.WARNING);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export failed");
                    al.showAndWait();
                }
                mc.selectStep(6);
            }
        });
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeStepSummary(MainController mc, int factSheetIdx) {
    Node n = mc.goToFactSheet(factSheetIdx, false);
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }//w  w w. j a v  a 2 s  . co  m
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {

        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();
        //Scene scene = new Scene(bp);
        //n.applyCss();
        //bp.applyCss();
        //WritableImage wi = scene.snapshot(null);

        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

        double prefHeight = wi.getHeight();
        double prefWidth = wi.getWidth();

        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        boolean exportSuccess = false;
        try {
            //ImageIO.write(bi, "png", new File("test.png"));
            PDPageContentStream content = new PDPageContentStream(doc, page);
            PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
            int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
            int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
            int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
            drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
            content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth, drawHeight);
            content.fillAndStroke();
            content.close();
            drawReportHeaderFooter(doc, mc.getProject(), true);
            doc.save(saveFile);
            doc.close();
            exportSuccess = true;
        } catch (IOException ie) {
            System.out.println("ERROR");
        }
        if (exportSuccess) {
            Alert al = new Alert(Alert.AlertType.CONFIRMATION);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export successful");
            al.showAndWait();
        } else {
            Alert al = new Alert(Alert.AlertType.WARNING);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export failed");
            al.showAndWait();
        }
    }
}

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

License:Open Source License

public static <T> void draw(VennFigure<T> vennFigure, PDDocument doc, PDPage page, PDFont font,
        PDRectangle rect) throws IOException {
    PDPageContentStream contents = new PDPageContentStream(doc, page);

    Rectangle2D drawRect = vennFigure.drawRect(str -> stringBoundingBox(font, str, FONT_SIZE));
    PointConverter.JoinedConverter pointConverter = new PointConverter.JoinedConverter();
    pointConverter/* www  . j av a  2  s . c o m*/
            .addLast(new PointConverter.Translate(-drawRect.getMinX() + MARGIN, -drawRect.getMinY() + MARGIN));
    pointConverter.addLast(new PointConverter.Scale(1, -1));
    pointConverter.addLast(new PointConverter.Translate(0, rect.getHeight()));

    // fill first
    for (VennFigure.Shape<T> shape : vennFigure.getShapes()) {
        if (shape instanceof VennFigure.Oval) {
            VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape;

            Color fillColor = VennDrawGraphics2D.decodeColor(oval.getColor());
            if (fillColor.getAlpha() == 0)
                continue;

            //COSName graphicsStateName = page.getResources().add(graphicsState);

            List<VennFigure.Point> polygon = oval.toPolygon();

            VennFigure.Point converted = pointConverter.convert(polygon.get(0));
            contents.moveTo((float) converted.getX(), (float) converted.getY());
            polygon.add(polygon.remove(0)); // move to last
            for (VennFigure.Point p : polygon) {
                converted = pointConverter.convert(p);
                contents.lineTo((float) converted.getX(), (float) converted.getY());
            }

            if (fillColor.getAlpha() != 255) {
                PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
                graphicsState.setNonStrokingAlphaConstant(fillColor.getAlpha() / 255.f);
                contents.saveGraphicsState();
                contents.setGraphicsStateParameters(graphicsState);
            }

            contents.setNonStrokingColor(fillColor);
            contents.fill();

            if (fillColor.getAlpha() != 255) {
                contents.restoreGraphicsState();
            }

        }
    }

    for (VennFigure.Shape<T> shape : vennFigure.getShapes()) {
        if (shape instanceof VennFigure.Oval) {
            VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape;
            List<VennFigure.Point> polygon = oval.toPolygon();

            VennFigure.Point converted = pointConverter.convert(polygon.get(0));
            contents.moveTo((float) converted.getX(), (float) converted.getY());
            polygon.add(polygon.remove(0)); // move to last
            for (VennFigure.Point p : polygon) {
                converted = pointConverter.convert(p);
                contents.lineTo((float) converted.getX(), (float) converted.getY());
            }

            contents.setNonStrokingColor(Color.BLACK);
            contents.stroke();
        } else if (shape instanceof VennFigure.Text) {
            VennFigure.Text<T> text = (VennFigure.Text<T>) shape;

            Rectangle2D boundingBox = stringBoundingBox(font, text.getText(), FONT_SIZE);
            VennFigure.Point converted = pointConverter.convert(text.getCenter());

            float xOffset;
            switch (text.getJust()) {
            case CENTER:
                xOffset = (float) (-boundingBox.getWidth() / 2);
                break;
            case RIGHT:
                xOffset = (float) (-boundingBox.getWidth());
                break;
            default:
                xOffset = 0;
                break;
            }

            contents.beginText();
            contents.setNonStrokingColor(Color.BLACK);
            contents.setFont(font, FONT_SIZE);
            contents.newLineAtOffset((float) (converted.getX() + xOffset),
                    (float) (converted.getY() - boundingBox.getHeight() / 2));
            contents.showText(text.getText());
            contents.endText();
        }
    }

    contents.saveGraphicsState();
    contents.close();
}

From source file:jgnash.PDFBoxTableTest.java

License:Open Source License

@Test
void simpleTest() throws IOException {

    Path tempPath = null;/*  www  . ja v  a 2 s  . com*/

    try (PDDocument doc = new PDDocument()) {
        tempPath = Files.createTempFile("test", ".pdf");
        System.out.println(tempPath);

        PDPage page = new PDPage();
        doc.addPage(page);

        PDFont font = PDType1Font.HELVETICA;

        try (final PDPageContentStream contents = new PDPageContentStream(doc, page)) {
            contents.beginText();
            contents.setFont(font, 11);
            contents.newLineAtOffset(100, 700);
            contents.showText("Hello World!");
            contents.endText();
        }

        doc.save(tempPath.toFile());
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (tempPath != null) {
            Files.deleteIfExists(tempPath);
        }
    }
}

From source file:jp.qpg.PDFPrinter.java

License:Apache License

/**
 * @return PDF content//from  w  w  w  .  j  a v  a  2 s.c om
 */
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;/*from  w  w  w  .  ja va2 s . com*/
    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);
    }
}