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

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

Introduction

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

Prototype

public void save(OutputStream output) throws IOException 

Source Link

Document

This will save the document to an output stream.

Usage

From source file:correccioncolorpdfs.CorrectorColorUI.java

private void transformarPDF() {
    try {/*w  w w .  j a  va 2  s . co  m*/
        //@see http://stackoverflow.com/questions/18189314/convert-a-pdf-file-to-image
        String rutaPDFOriginal = rutaPDF + nombrePDF; // Pdf files are read from this folder
        //String destinationDir = "D:\\Desarrollo\\pruebas\\reportes_negros\\imagenes\\"; // converted images from pdf document are saved here

        File pdfOriginal = new File(rutaPDFOriginal);
        //            File destinationFile = new File(destinationDir);
        //            if (!destinationFile.exists()) {
        //                destinationFile.mkdir();
        //                System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
        //            }
        if (pdfOriginal.exists()) {
            //System.out.println("Images copied to Folder: " + destinationFile.getName());
            PDDocument document = PDDocument.load(rutaPDFOriginal);

            //Documento Fondo Blanco
            PDDocument documentoCool = new PDDocument();

            List<PDPage> list = document.getDocumentCatalog().getAllPages();
            System.out.println("Total files to be converted -> " + list.size());

            String nombrePDFOriginal = pdfOriginal.getName().replace(".pdf", "");
            int pageNumber = 1;
            for (PDPage page : list) {
                BufferedImage image = page.convertToImage();

                //Inviertiendo colores
                //@see http://stackoverflow.com/questions/8662349/convert-negative-image-to-positive
                for (int x = 0; x < image.getWidth(); x++) {
                    for (int y = 0; y < image.getHeight(); y++) {
                        int rgba = image.getRGB(x, y);
                        //Hexa a reemplazar e9e9e1 R=233|G=233|B=225
                        Color col = new Color(rgba, true);
                        col = new Color(255 - col.getRed(), 255 - col.getGreen(), 255 - col.getBlue());

                        //Si color es igual al invertido - cambiarlo a blanco
                        if (col.getRGB() == -1447455) {
                            col = new Color(255, 255, 255);
                        }
                        //System.out.println("col.getR = " + col.getRGB());
                        image.setRGB(x, y, col.getRGB());
                    }
                }
                //                    File outputfile = new File(destinationDir + fileName + "_" + pageNumber + ".png");
                //                    System.out.println("Image Created -> " + outputfile.getName());
                //                    ImageIO.write(image, "png", outputfile);
                pageNumber++;

                //Crear pagina nueva para el PDF Convertido
                float width = image.getWidth();
                float height = image.getHeight();
                PDPage paginaSinFondo = new PDPage(new PDRectangle(width, height));
                documentoCool.addPage(paginaSinFondo);
                PDXObjectImage img = new PDJpeg(documentoCool, image);
                PDPageContentStream contentStream = new PDPageContentStream(documentoCool, paginaSinFondo);
                contentStream.drawImage(img, 0, 0);
                contentStream.close();

            }
            document.close();
            rutaPDFImprimible = rutaPDF + nombrePDFOriginal + "_imprimible.pdf";
            documentoCool.save(rutaPDFImprimible);
            documentoCool.close();

            estadoConversion(true);
        } else {
            JOptionPane.showMessageDialog(this,
                    "No se logr identificar la ruta del archivo, por favor verifique que el archivo si existe o no halla sido movido durante el proceso.",
                    "Ruta de archivo no encontrada", JOptionPane.WARNING_MESSAGE);
        }

    } catch (IOException | COSVisitorException | HeadlessException e) {
        estadoConversion(false);
        JOptionPane.showMessageDialog(this, e.getMessage(), "Error durante el proceso de conversin",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:cr.ac.siua.tec.utils.PDFGenerator.java

License:Open Source License

/**
 * Encodes PDF object (PDDocument) to base4.
 *///  w  w w  .  jav a2s .  c o m
public String encodePDF(PDDocument document) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        document.save(out);
        document.close();
    } catch (COSVisitorException | IOException e) {
        e.printStackTrace();
    }
    byte[] bytes = out.toByteArray();
    byte[] encoded = Base64.encodeBase64(bytes);
    return new String(encoded);
}

From source file:CTRL.ExportController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w.  j ava 2 s  . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession session = request.getSession();

    LijstLesmomentenViewModel vmLesmomentenFinal = (LijstLesmomentenViewModel) session
            .getAttribute("vmLesmomentenFinal");

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    contentStream.beginText();
    contentStream.setFont(font, 16);
    contentStream.moveTextPositionByAmount(60, 700);

    // Titel
    contentStream.drawString("Lessenrooster");

    contentStream.setFont(font, 10);
    contentStream.moveTextPositionByAmount(0, -20);

    int recordTeller = 0;
    for (Lesmoment l : vmLesmomentenFinal.getLesmomenten()) {

        Calendar c = Calendar.getInstance();
        c.setTime(l.getDatum());
        int dag = c.get(Calendar.DAY_OF_WEEK);

        String strDag = "";

        switch (dag) {
        case 0:
            strDag = "Zondag";
            break;
        case 1:
            strDag = "Maandag";
            break;
        case 2:
            strDag = "Dinsdag";
            break;
        case 3:
            strDag = "Woensdag";
            break;
        case 4:
            strDag = "Donderdag";
            break;
        case 5:
            strDag = "Vrijdag";
            break;
        case 6:
            strDag = "Zaterdag";
            break;
        }

        //Nieuwe page beginnen wanner 25 records werden weggeschreven
        if (recordTeller == 25) {
            recordTeller = 0;
            contentStream.endText();
            contentStream.close();

            page = new PDPage();
            document.addPage(page);
            contentStream = new PDPageContentStream(document, page);
            contentStream.beginText();
            contentStream.setFont(font, 10);
            contentStream.moveTextPositionByAmount(60, 700);
        } else {
            recordTeller++;
        }

        contentStream.drawString(l.getDatum().toString() + "     " + strDag + "     " + l.getBeginuur()
                + "     " + l.getEinduur() + "     " + l.getLokaal() + "     " + l.getModule().getCode()
                + "     " + l.getModule().getNaam());
        contentStream.moveTextPositionByAmount(0, -20);
    }

    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    try {
        // Save the results and ensure that the document is properly closed:
        document.save("C:\\Temp\\test.pdf");
    } catch (COSVisitorException ex) {
        Logger.getLogger(ExportController.class.getName()).log(Level.SEVERE, null, ex);
    }
    document.close();

    //Teruggaan naar resultaat pagina
    RequestDispatcher dispatcher = request.getRequestDispatcher("Resultaat.jsp");
    dispatcher.forward(request, response);
}

From source file:de.berber.kindle.annotator.lib.PDFAnnotator.java

License:Apache License

@SuppressWarnings("unchecked")
public boolean run() {
    // read all annotations
    final List<Annotation> annotations = new KindleAnnotationReader(cc, pdfFile).read();

    if (annotations.size() == 0) {
        return true;
    }//  w w w .j av  a 2s  . c om

    PDDocument document = null;
    // annotate pdf
    try {
        document = PDDocument.load(pdfFile);

        //inDocument.decrypt(pass);
        // get outline for bookmarks
        PDDocumentOutline documentOutline = document.getDocumentCatalog().getDocumentOutline();

        if (documentOutline == null) {
            // if there is no document outline we have to create a new one.
            documentOutline = new PDDocumentOutline();
            document.getDocumentCatalog().setDocumentOutline(documentOutline);
        }

        assert documentOutline != null;

        // convert annotations for each page
        int pageNumber = 0;
        for (PDPage page : (List<PDPage>) document.getDocumentCatalog().getAllPages()) {
            for (final Annotation dxAnn : annotations) {
                dxAnn.toPDAnnotation(pageNumber, documentOutline, page);
            }

            pageNumber++;
        }

        //inDocument.setAllSecurityToBeRemoved(true);
        document.save(outFile.toString());
    } catch (FileNotFoundException e) {
        LOG.error("Could not find input file " + pdfFile);
        return false;
    } catch (IOException e) {
        LOG.error("IOError while writing result file " + outFile);
        return false;
    } catch (COSVisitorException e) {
        LOG.error("PDFBox error while storing result file " + outFile);
        return false;
    } finally {
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
                LOG.error("Error while closing PDF document " + pdfFile);
            }
        }
    }

    return true;
}

From source file:de.fau.amos4.util.ZipGenerator.java

License:Open Source License

public void generate(OutputStream out, Locale locale, float height, Employee employee, int fontSize,
        String zipPassword) throws ZipException, NoSuchMessageException, IOException, COSVisitorException,
        CloneNotSupportedException {
    final ZipOutputStream zout = new ZipOutputStream(out);

    if (zipPassword == null) {
        // Use default password if none is set.
        zipPassword = "fragebogen";
    }//w w w.  jav a 2s .  c  o m

    ZipParameters params = new ZipParameters();
    params.setFileNameInZip("employee.txt");
    params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
    params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
    params.setEncryptFiles(true);
    params.setReadHiddenFiles(false);
    params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
    params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
    params.setPassword(zipPassword);
    params.setSourceExternalStream(true);

    zout.putNextEntry(null, params);
    zout.write((AppContext.getApplicationContext().getMessage("HEADER", null, locale) + "\n\n").getBytes());

    zout.write(
            (AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n")
                    .getBytes());

    Iterator it = employee.getPersonalDataFields().entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
        it.remove(); // avoids a ConcurrentModificationException
    }

    zout.write(("\n\n" + AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale)
            + "\n\n").getBytes());

    it = employee.getTaxesFields().entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
        it.remove(); // avoids a ConcurrentModificationException
    }
    zout.closeEntry();

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    float y = -1;
    int margin = 100;

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.TIMES_ROMAN;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    contentStream.beginText();

    y = page.getMediaBox().getHeight() - margin + height;
    contentStream.moveTextPositionByAmount(margin, y);
    /*
    List<String> list = StringUtils.splitEqually(fileContent, 90);
    for (String e : list) {
        contentStream.moveTextPositionByAmount(0, -15);
        contentStream.drawString(e);
    }
    */

    contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
    contentStream.drawString(AppContext.getApplicationContext().getMessage("HEADER", null, locale));
    contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
    contentStream.moveTextPositionByAmount(0, -4 * height);
    contentStream.drawString(
            AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream.setFont(font, fontSize);

    it = employee.getPersonalDataFields().entrySet().iterator();
    while (it.hasNext()) {
        StringBuffer nextLineToDraw = new StringBuffer();
        Map.Entry pair = (Map.Entry) it.next();
        nextLineToDraw.append(pair.getKey());
        nextLineToDraw.append(": ");
        nextLineToDraw.append(pair.getValue());

        contentStream.drawString(nextLineToDraw.toString());
        contentStream.moveTextPositionByAmount(0, -height);
        it.remove(); // avoids a ConcurrentModificationException
    }
    contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream
            .drawString(AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale));
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream.setFont(font, fontSize);
    it = employee.getTaxesFields().entrySet().iterator();
    while (it.hasNext()) {
        StringBuffer nextLineToDraw = new StringBuffer();
        Map.Entry pair = (Map.Entry) it.next();
        nextLineToDraw.append(pair.getKey());
        nextLineToDraw.append(": ");
        nextLineToDraw.append(pair.getValue());

        contentStream.drawString(nextLineToDraw.toString());
        contentStream.moveTextPositionByAmount(0, -height);
        it.remove(); // avoids a ConcurrentModificationException
    }
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    // Save the results and ensure that the document is properly closed:
    ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
    document.save(pdfout);
    document.close();

    ZipParameters params2 = (ZipParameters) params.clone();
    params2.setFileNameInZip("employee.pdf");

    zout.putNextEntry(null, params2);
    zout.write(pdfout.toByteArray());
    zout.closeEntry();

    // Write the zip to client
    zout.finish();
    zout.flush();
    zout.close();
}

From source file:de.fau.amos4.web.PrintDataController.java

License:Open Source License

@RequestMapping("/employee/download/zip")
public void EmployeeDownloadZip(HttpServletResponse response,
        @RequestParam(value = "id", required = true) long employeeId) throws IOException {
    int fontSize = 12;
    float height = 1;
    height = height * fontSize * 1.05f;/*w  w  w  .jav a2s . c o m*/

    //Prepare textfile contents
    Employee employee = employeeRepository.findOne(employeeId);
    Locale locale = LocaleContextHolder.getLocale();
    Map<String, String> fields = employee.getFields();

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment;filename=employee.zip");

    final ZipOutputStream zout = new ZipOutputStream(response.getOutputStream());

    try {
        ZipParameters params = new ZipParameters();
        params.setFileNameInZip("employee.txt");
        params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
        params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
        params.setEncryptFiles(true);
        params.setReadHiddenFiles(false);
        params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
        params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
        params.setPassword("AMOS");
        params.setSourceExternalStream(true);

        zout.putNextEntry(null, params);
        zout.write((AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale) + "\n\n")
                .getBytes());
        //zout.println();
        zout.write((AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale)
                + "\n\n").getBytes());
        //zout.println();
        Iterator it = fields.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
            it.remove(); // avoids a ConcurrentModificationException
        }
        zout.closeEntry();

        try {
            // Create a document and add a page to it
            PDDocument document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
            float y = -1;
            int margin = 100;
            float maxStringLength = page.getMediaBox().getWidth() - 2 * margin;

            // Create a new font object selecting one of the PDF base fonts
            PDFont font = PDType1Font.TIMES_ROMAN;

            // Start a new content stream which will "hold" the to be created content
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
            contentStream.beginText();

            y = page.getMediaBox().getHeight() - margin + height;
            contentStream.moveTextPositionByAmount(margin, y);
            /*
            List<String> list = StringUtils.splitEqually(fileContent, 90);
            for (String e : list) {
            contentStream.moveTextPositionByAmount(0, -15);
            contentStream.drawString(e);
            }
            */

            fields = employee.getFields();

            contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
            contentStream.drawString(
                    AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale));
            contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
            contentStream.moveTextPositionByAmount(0, -4 * height);
            contentStream.drawString(
                    AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
            contentStream.moveTextPositionByAmount(0, -2 * height);
            contentStream.setFont(font, fontSize);
            it = fields.entrySet().iterator();
            while (it.hasNext()) {
                StringBuffer nextLineToDraw = new StringBuffer();
                Map.Entry pair = (Map.Entry) it.next();
                nextLineToDraw.append(pair.getKey());
                nextLineToDraw.append(": ");
                nextLineToDraw.append(pair.getValue());

                contentStream.drawString(nextLineToDraw.toString());
                contentStream.moveTextPositionByAmount(0, -height);
                it.remove(); // avoids a ConcurrentModificationException
            }
            contentStream.endText();

            // Make sure that the content stream is closed:
            contentStream.close();

            // Save the results and ensure that the document is properly closed:
            ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
            document.save(pdfout);
            document.close();

            ZipParameters params2 = (ZipParameters) params.clone();
            params2.setFileNameInZip("employee.pdf");

            zout.putNextEntry(null, params2);
            zout.write(pdfout.toByteArray());
            zout.closeEntry();
        } catch (CloneNotSupportedException | COSVisitorException e) {
            e.printStackTrace();
        }

        // Write the zip to client
        zout.finish();
        zout.flush();
        zout.close();
    } catch (ZipException e) {
        e.printStackTrace();
    }
}

From source file:de.hrogge.CompactPDFExport.PDFGenerator.java

License:Apache License

public void exportierePDF(JFrame frame, File output, Document input, Konfiguration k, boolean speichernDialog)
        throws IOException, COSVisitorException, JAXBException {
    PDDocument doc = null;

    /* JAXB Reprsentation des XML-Dokuments erzeugen */
    JAXBContext jaxbContext = JAXBContext.newInstance(jaxbGenerated.datenxml.Daten.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Daten daten = (Daten) jaxbUnmarshaller.unmarshal(input.getDocumentElement());

    try {//from  w ww .  j  a  v  a  2 s.  co m
        doc = internErzeugePDFDokument(k, daten);

        if (output == null) {
            String ordner = k.getTextDaten(Konfiguration.GLOBAL_ZIELORDNER);
            if (speichernDialog) {
                output = waehlePDFFile(frame, daten, ordner);
                if (output == null) {
                    return;
                }
            } else {
                output = new File(ordner, daten.getAngaben().getName() + ".pdf");
            }
        }

        if (output.exists()) {
            int result = JOptionPane.showConfirmDialog(frame,
                    "Die Datei " + output.getAbsolutePath()
                            + " existiert schon.\nSoll sie berschrieben werden?",
                    "Datei berschreiben?", JOptionPane.YES_NO_OPTION);

            if (result != JOptionPane.YES_OPTION) {
                return;
            }
        }

        doc.save(new FileOutputStream(output));
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:de.ifsr.adam.ImageGenerator.java

License:Open Source License

/**
 * Takes a snapshot of the Pane and prints it to a pdf.
 *
 * @return True if no IOException occurred
 *//*from   w  w  w.ja  v a 2s  .  c  om*/
private boolean printToPDF(String filePath, Pane pane) {
    //Scene set up
    Group root = new Group();
    Scene printScene = new Scene(root);
    printScene.getStylesheets().add(this.stylesheetURI.toString());

    //Snapshot generation
    ArrayList<WritableImage> images = new ArrayList<>();
    try {
        ObservableList<Node> panes = pane.getChildren();
        for (int i = 0; i < panes.size(); i++) {
            GridPane gridPane = (GridPane) panes.get(i);
            ((Group) printScene.getRoot()).getChildren().clear();
            ((Group) printScene.getRoot()).getChildren().addAll(gridPane);
            images.add(printScene.snapshot(null));
            panes.add(i, gridPane);
        }
    } catch (Exception e) {
        log.error(e);
        return false;
    }

    //PDF Setup
    File outFile = new File(filePath + "." + "pdf");
    Iterator<WritableImage> iterImages = images.iterator();
    PDDocument doc = new PDDocument();

    try {

        while (iterImages.hasNext()) {
            //Page setup
            PDPage page = new PDPage();
            doc.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            //Image setup
            BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null);
            PDPixelMap pixelMap = new PDPixelMap(doc, bufImage);

            int width = (int) (page.getMediaBox().getWidth());
            int height = (int) (page.getMediaBox().getHeight());
            Dimension dim = new Dimension(width, height);
            contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height);
            contentStream.close();
        }

        doc.save(outFile);
        return true;
    } catch (IOException | COSVisitorException e) {
        log.error(e);
        return false;
    }
}

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  www.j  av a 2s  .  c o 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  w w .  j a  v 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();
        }
    }

}