Example usage for org.apache.pdfbox.pdmodel PDDocument close

List of usage examples for org.apache.pdfbox.pdmodel PDDocument close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

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.
 * //w ww  .j a v  a2  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:de.maklerpoint.office.Schnittstellen.PDF.ExportSimplePDF.java

License:Open Source License

public void write() throws IOException, COSVisitorException {
    PDDocument doc = null;
    try {//from  w ww.j av  a2  s  .c o m
        doc = new PDDocument();

        PDPage page = new PDPage();
        doc.addPage(page);
        PDFont font = PDType1Font.HELVETICA;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(contents);

        contentStream.endText();
        contentStream.close();

        doc.save(filename);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }

}

From source file:de.micromata.genome.gwiki.plugin.pdftextextractor_1_0.PdfTextExtractor.java

License:Apache License

public String extractText(String fileName, InputStream data) {
    try {/*w  w w .j  a  v a2 s  .  com*/
        PDDocument doc = PDDocument.load(data);
        PDFTextStripper st = new PDFTextStripper("UTF-8");
        StringWriter sout = new StringWriter();
        st.writeText(doc, sout);
        doc.close();
        return sout.getBuffer().toString();
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
}

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

License:Open Source License

@Override
public synchronized Preview createPreviewFor(File aFile) {
    PDDocument theDocument = null;
    try {//from  w ww .jav a 2  s.com
        theDocument = PDDocument.load(aFile);
        List<?> thePages = theDocument.getDocumentCatalog().getAllPages();
        if (thePages.isEmpty()) {
            return null;
        }
        PDPage theFirstPage = (PDPage) thePages.get(0);

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

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

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

From source file:de.offis.health.icardea.cied.pdf.extractor.PDFApachePDFBoxExtractor.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] getPDFPages(int fromPageNumber, int toPageNumber) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    boolean extractionSuccessful = false;

    if (pdfDocument != null) {
        int numberOfPages = getNumberOfPages();

        /*/*from   w  w  w . ja  v a  2 s.  co  m*/
         * Check if the given page numbers are in the allowed range.
         */
        if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0
                && toPageNumber <= numberOfPages) {
            /*
             * Now check if the given fromPageNumber is smaller
             * as the given toPageNumber. If not swap the numbers.
             */
            if (fromPageNumber > toPageNumber) {
                int tmpPageNumber = toPageNumber;
                toPageNumber = fromPageNumber;
                fromPageNumber = tmpPageNumber;
            }

            /*
             * Now extract the pages
             * 
             * NOTE
             * ====
             * Since Apache PDFBox v1.5.0 there exists the class
             * org.apache.pdfbox.util.PageExtractor
             */

            /*
            boolean isApachePageExtractorAvailable = false;
            Class<?> pageExtractorClass = null;
            try {
               pageExtractorClass = getClass().getClassLoader().loadClass("org.apache.pdfbox.util.PageExtractor");
               Constructor<?> pdfExtractConstructor = pageExtractorClass.getConstructor(PDDocument.class, int.class, int.class);
               Method pdfExtractMethod = pageExtractorClass.getMethod("extract");
               isApachePageExtractorAvailable = true;
            } catch (ClassNotFoundException ex) {
            } catch (SecurityException ex) {
            } catch (NoSuchMethodException ex) {
            }
            */

            try {
                PDDocument extractedDocumentPages = new PDDocument();
                extractedDocumentPages.setDocumentInformation(this.pdfDocument.getDocumentInformation());
                extractedDocumentPages.getDocumentCatalog()
                        .setViewerPreferences(this.pdfDocument.getDocumentCatalog().getViewerPreferences());

                List<PDPage> pages = (List<PDPage>) this.pdfDocument.getDocumentCatalog().getAllPages();
                int pageCounter = 1;
                for (PDPage page : pages) {
                    if (pageCounter >= fromPageNumber && pageCounter <= toPageNumber) {
                        PDPage importedPdfPage;
                        importedPdfPage = extractedDocumentPages.importPage(page);
                        importedPdfPage.setCropBox(page.findCropBox());
                        importedPdfPage.setMediaBox(page.findMediaBox());
                        importedPdfPage.setResources(page.findResources());
                        importedPdfPage.setRotation(page.findRotation());
                    }
                    pageCounter++;
                } // end for

                byteArrayOutputStream = new ByteArrayOutputStream();
                extractedDocumentPages.save(byteArrayOutputStream);
                extractedDocumentPages.close();
                extractionSuccessful = true;
            } catch (COSVisitorException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } catch (IOException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } finally {
                if (!extractionSuccessful) {
                    byteArrayOutputStream = null;
                }
            } // end try..catch..finally
        } // end if checking range of given pages
    } // end if (pdfDocument != null)

    if (byteArrayOutputStream != null) {
        return byteArrayOutputStream.toByteArray();
    }
    return null;
}

From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DTestBase.java

License:Apache License

@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
    try {/*  w  w  w  .ja  va  2s . c o m*/
        PDDocument document = new PDDocument();

        PDFont pdArial = PDFontFactory.createDefaultFont();

        File parentDir = new File("target/test/" + dir);
        // noinspection ResultOfMethodCallIgnored
        parentDir.mkdirs();

        BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D imageGraphics = image.createGraphics();
        exporter.draw(imageGraphics);
        imageGraphics.dispose();
        ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

        for (Mode m : Mode.values()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
            PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
            contentStream.beginText();
            contentStream.setStrokingColor(0, 0, 0);
            contentStream.setNonStrokingColor(0, 0, 0);
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
            contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
            contentStream.showText("Mode " + m);
            contentStream.endText();
            switch (m) {
            case FontTextIfPossible:
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
                registerFots(fontTextDrawer);
                break;
            case DefaultFontText: {
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
                registerFots(fontTextDrawer);
                break;
            }
            case ForceFontText:
                fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
                registerFots(fontTextDrawer);
                fontTextDrawer.registerFont("Arial", pdArial);
                break;
            case DefaultVectorized:
            default:
                break;
            }

            if (fontTextDrawer != null) {
                pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
            }

            exporter.draw(pdfBoxGraphics2D);
            pdfBoxGraphics2D.dispose();

            PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
            Matrix matrix = new Matrix();
            matrix.translate(0, 20);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);

            matrix.scale(1.5f, 1.5f);
            matrix.translate(0, 100);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);
            contentStream.close();
        }

        document.save(new File(parentDir, name + ".pdf"));
        document.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

public void createPDF() {

    String filename = "Rechnung-" + bill.getId() + ".pdf";

    try {//from   w  ww .j  a  v a 2s .  co  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("Rechnungsprfung");
        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(70, 540);
        content.showText("Rechnung " + bill.getId() + " fuer KN " + fiCustomer.getId());
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 520);
        content.showText("Sehr geehrte Damen und Herren, ");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 500);
        content.showText("hiermit erlauben wir uns fr unsere Lieferung Nr. " + deliveryNote.getId() + " vom "
                + deliveryNote.getDate());
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, 485);
        content.showText("folgenden Betrag in Rechnung zu stellen:");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(75, 470);
        content.showText("POS");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(120, 470);
        content.showText("Bezeichnung");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(440, 470);
        content.showText("Preis");
        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();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 12);
            content.newLineAtOffset(440, yoffset - 20);
            content.showText("Eur " + product.getPrice() * ((100 - license.getDiscount()) / 100));
            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();
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 12);
                content.newLineAtOffset(440, yoffset - 40);
                content.showText("Eur " + maintenance.getPrice());
                content.endText();
            }
            count++;
            yoffset -= 100;
        }

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Summe ");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(440, yoffset);
        content.showText(String.valueOf("EUR " + bill.getPrice()));
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("USt. 19%");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(440, yoffset);
        double ust = (bill.getPrice() * 0.19);
        content.showText(String.valueOf("EUR " + ust));
        content.endText();
        yoffset -= 20;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Gesamtsumme");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(440, yoffset);
        double priceTotal = bill.getPrice() + ust;
        content.showText(String.valueOf("EUR " + priceTotal));
        content.endText();
        yoffset -= 40;

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("Wir bitten Sie, den Gesamtbetrag von EUR " + priceTotal + " auf unser Konto 123456,");
        content.endText();
        yoffset -= 20;
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 12);
        content.newLineAtOffset(70, yoffset);
        content.showText("bei der Bank Unserort, BLZ4321, IBAN123 zu berweisen. Zahlungsziel: 30 Tage netto.");
        content.endText();
        yoffset -= 25;

        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:de.schneefisch.fruas.transactions.DeliveryNotePDFCreator.java

public void createPDF() {

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

    try {/*from w w w . j  a v  a  2s  .  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:de.thb.ue.backend.util.PDFGeneration.java

License:Apache License

public static void createQRCPDF(List<BufferedImage> tickets, String evaluationUID, String subject,
        SemesterType semesterType, int year, File workingDirectory) {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    //        PDRectangle rectangle = new PDRectangle(page.findCropBox().getWidth(), 500);
    //        page.setCropBox(rectangle);

    document.addPage(page);//w  w w  . j av  a 2s  .  co  m
    PDXObjectImage pdImage;

    try {
        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        int x = 0;
        // start from top of page instead of bottom
        // somehow the first row gets swallowed -> start with second row instead
        int y = (int) page.findCropBox().getHeight() - (new PDJpeg(document, tickets.get(0))).getHeight();

        int imageHeight;
        int imageWidth;
        String qrCodePurpose = "Evaluation QR-Codes fr das Fach " + subject + " im "
                + (semesterType == SemesterType.WINTER ? "Winter" : "Sommer") + "semester "
                + Integer.toString(year);
        PDFont font = PDType1Font.HELVETICA;
        int fontSize = 13;

        // center text horizontally
        float textWidth = font.getStringWidth(qrCodePurpose) / 1000 * fontSize;
        int textX = (int) ((page.findCropBox().getWidth() / 2) - (textWidth / 2));

        // add QR-Codes
        for (int i = 0; i < tickets.size(); i++) {

            pdImage = new PDJpeg(document, tickets.get(i));
            imageHeight = pdImage.getHeight();
            imageWidth = pdImage.getWidth();

            if ((imageWidth + x) > page.findCropBox().getWidth()) {
                x = 0;
                y -= imageHeight;
            }

            if (y <= 0) {
                writeText(contentStream, page, qrCodePurpose, imageHeight, textX,
                        (y + imageHeight) - (imageHeight / 4), fontSize, font);
                page = new PDPage();
                document.addPage(page);
                contentStream.close();
                contentStream = new PDPageContentStream(document, page);
                y = (int) page.findCropBox().getHeight() - pdImage.getHeight();
                x = 0;
            }

            contentStream.drawImage(pdImage, x, y);

            if (i + 1 >= tickets.size()) {
                writeText(contentStream, page, qrCodePurpose, imageHeight, textX, y - 20, fontSize, font);
            }
            x += imageWidth;
        }

        /*PDDocumentCatalog catalog = document.getDocumentCatalog();
        catalog.getAcroForm().setXFA(null);*/

        contentStream.close();
        if (!workingDirectory.exists()) {
            workingDirectory.mkdir();
        }
        File outputFile = new File(workingDirectory, "qrcodes.pdf");
        document.save(outputFile);

    } catch (IOException | COSVisitorException e) {
        e.printStackTrace();
    } finally {
        try {
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.pdf.Pdf2CasConverter.java

License:Apache License

public void writeText(final CAS aCas, final InputStream aIs) throws IOException {
    final PDDocument doc = PDDocument.load(aIs);

    try {/*from  ww w  .  j ava 2 s  .  c  o m*/
        if (doc.isEncrypted()) {
            throw new IOException("Encrypted documents currently not supported");
        }

        cas = aCas;
        text = new StringBuilder();

        writeText(doc);
    } finally {
        doc.close();
    }
}