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() 

Source Link

Document

Creates a new PDPage instance for embedding, with a size of U.S.

Usage

From source file:controller.PDFServlet.java

License:Apache License

/**
 * This method processes requests from the progress note page for both HTTP
 * <code>GET</code> and <code>POST</code> methods. The progress note data
 * retrieved from the request is written as a PDF document.
 *
 * @param request servlet request// w  ww.  j  a  v a2 s  . c  om
 * @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 {
    HttpSession session = request.getSession();
    ProgressNote progressNote = (ProgressNote) session.getAttribute(SessionObjectUtility.PROGRESS_NOTE);
    Patient patient = progressNote.getPatient();
    response.setContentType("text/html;charset=UTF-8");
    int yPosition = 705;
    int xPosition = 70;
    int lineCount;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String yesOrNo;
    String nextYesOrNo;
    try (PDDocument doc = new PDDocument()) {

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

        try {
            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TITLE_FONT_SIZE);
            content.moveTextPositionByAmount(225, MAXIMUM_Y_POSITION);
            content.drawString("Progress Note");
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, DATE_FONT_SIZE);
            content.moveTextPositionByAmount(245, 725);
            content.drawString(progressNote.getDateCreated().toString());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Patient Name: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(patient.getFirstName() + " " + patient.getLastName());
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Telephone: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(patient.getContactNumber()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   DOB: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + patient.getBirthDate());
            content.endText();

            String[] noteLines = getNoteLines((String) nullCheck(progressNote.getPatient().getAddress()),
                    ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Address: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            noteLines = getNoteLines((String) nullCheck(patient.getEmailAddress()), ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Email Address: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            if (progressNote.getAllergicToMedications() == true) {
                yesOrNo = "yes";
            } else {
                yesOrNo = "no";
            }
            if (progressNote.getMedicalInsurance() == true) {
                nextYesOrNo = "yes";
            } else {
                nextYesOrNo = "no";
            }

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Allergic to medications: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(yesOrNo);
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("  Medical Insurance: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(nextYesOrNo);
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Shoe Size: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getShoeSize()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Allergies: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getAllergies()));
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getMedications()), ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= 20;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Medications: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Weight(lbs): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getWeight()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Height(in.): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            if ((progressNote.getHeightFeet() != null) && (progressNote.getHeightInches() != null)) {
                content.drawString(
                        "" + ((progressNote.getHeightFeet() * 12) + (progressNote.getHeightInches())));
            }
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   BMI: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getBmi()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Waist(in.): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getWaist()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   BP: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            if ((progressNote.getBloodPressureSystole() != null)
                    && (progressNote.getBloodPressureDiastole() != null)) {
                content.drawString(
                        progressNote.getBloodPressureSystole() + "/" + progressNote.getBloodPressureDiastole());
            }
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Pulse: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getPulse()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Respirations: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getRespirations()));
            content.endText();

            if (progressNote.getFootScreening() == true) {
                yesOrNo = "yes";
            } else {
                yesOrNo = "no";
            }
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Temperature: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getTemperature()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Foot Screening: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(yesOrNo);
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Glucose: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getGlucose()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("A1C: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getA1c()));
            content.endText();

            /* nurse or dietitian note */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Nurse/Dietitian Note: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getNurseOrDietitianNote()),
                    NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* subjective section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Subjective: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getSubjective()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* objective section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Objective: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getObjective()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* assessment section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Assessment: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getAssessment()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* plan section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Plan: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getPlan()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            for (NoteAuthor na : progressNote.getUpdatedBy()) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString("Updated by: ");
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(na.getFirstName() + " " + na.getLastName() + ", " + na.getJobTitle() + ", "
                        + na.getTimeStamp());
                content.endText();
            }
            content.close();
        } catch (IOException e) {
            Logger.getLogger(PDFServlet.class.getName()).log(Level.SEVERE,
                    "An IOException occurred when creating the PDF content.", e);
        }
        doc.addPage(page);
        doc.save(output);
        doc.close();
        String pdfFileName = "pdf-test.pdf";
        response.setContentType("application/pdf");
        response.addHeader("Content-Type", "application/force-download");
        response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);

        response.getOutputStream().write(output.toByteArray());

    } catch (IOException | COSVisitorException e) {
        Logger.getLogger(PDFServlet.class.getName()).log(Level.SEVERE,
                "An exception occurred when creating the PDF document.", e);
    }
}

From source file:CTRL.ExportController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w w .  j  a v a  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:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

public static PDDocument generateEmptyPdf() {
    PDDocument pdDocument = new PDDocument();
    pdDocument.addPage(new PDPage());
    return pdDocument;
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

private static PDPage generateGeoPdfPage(int numberOfFramesPerPage, String projectionType) {
    PDPage pdPage = new PDPage();
    COSDictionary cosDictionary = pdPage.getCOSObject();
    cosDictionary.setItem(GeoPdfParserImpl.LGIDICT,
            generateLGIDictArray(numberOfFramesPerPage, projectionType));
    return pdPage;
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

private static PDPage generateGeoPdfPage(String projectionType, boolean generateNeatLine) {
    PDPage pdPage = new PDPage();
    COSDictionary cosDictionary = pdPage.getCOSObject();
    cosDictionary.setItem(GeoPdfParserImpl.LGIDICT,
            generateMapFrameDictionary(projectionType, generateNeatLine));
    return pdPage;
}

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";
    }/*from  ww w  .j  ava  2 s  . co  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  . j a v 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.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. j a v a2 s  . co  m*/
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.maklerpoint.office.Schnittstellen.PDF.ExportSimplePDF.java

License:Open Source License

public void write() throws IOException, COSVisitorException {
    PDDocument doc = null;//  ww  w. ja va  2  s .  c  om
    try {
        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.schneefisch.fruas.transactions.BillPDFCreator.java

public void createPDF() {

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

    try {//ww w .  ja v  a2 s.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();
    }

}