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

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

Introduction

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

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$printPrescription</h3>
 * <p/>/*from w w  w . j  a va2 s  .  co  m*/
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param iPrescription Is an Interface of a prescription from which all the information will be printed into
 *                      a PDF-File and then started with standard application from OS.
 */
public void printPrescription(IPrescription iPrescription, IDoctor iDoctor) throws COSVisitorException,
        IOException, CantGetPresciptionEntriesException, NoPrescriptionToPrintException {
    if (iPrescription == null) {
        throw new NoPrescriptionToPrintException();
    }

    //instantiate a new document, create a page and add the page to the document
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rectangle = page1.getMediaBox();
    document.addPage(page1);

    //create fonts for the document
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate current line
    int line = 0;

    try {
        //new Stream to print into the file
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //print header (headlining)
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString("Prescription:");
        stream.endText();

        //get patient to print data from
        IPatient iPatient = iPrescription.getPatient();

        //write data from patient
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iPatient.getFirstName() + " " + iPatient.getLastName());
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        /* -- Team D: Add check on null -- */
        stream.drawString(iPatient.getBirthDay() == null ? "" : iPatient.getBirthDay().toString());
        /* -- -- -- */
        stream.endText();

        if (iPatient.getStreet() != null) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getStreet());
            stream.endText();
        }

        if ((iPatient.getPostalCode() != null) && (iPatient.getCity() != null)) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getPostalCode() + ", " + iPatient.getCity());
            stream.endText();
        }

        //next row
        ++line;

        //write data from doctor
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Prescription issued from doctor:");
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iDoctor.getTitle() + " " + iDoctor.getFirstName() + " " + iDoctor.getLastName());
        stream.endText();

        //next row
        ++line;

        //print all the entries in the prescription
        if (iPrescription.getPrescriptionEntries().size() > 0) {
            stream.beginText();
            stream.setFont(fontBold, 14);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString("Prescription Entries:");
            stream.endText();
            for (IPrescriptionEntry entry : iPrescription.getPrescriptionEntries()) {
                stream.beginText();
                stream.setFont(fontPlain, 12);
                stream.moveTextPositionByAmount(SPACING_LEFT,
                        rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
                stream.drawString("ID: " + entry.getId() + ", " + entry.getMedicine());
                stream.endText();
            }
        }

        //print oculus image into pdf file
        //Not working
        /*BufferedImage awtImage = ImageIO.read(new File("oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);*/

        //signature field

        ++line;
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Doctor's Signature:");
        stream.endText();

        //print a line for signature field
        stream.setLineWidth(0.5f);
        stream.addLine(SPACING_LEFT, rectangle.getHeight() - LINE_HEIGHT * (line += 2) - SPACING_HEADER,
                SPACING_LEFT + 100, rectangle.getHeight() - LINE_HEIGHT * (line) - SPACING_HEADER);
        stream.closeAndStroke();

        //close the stream
        stream.close();

        //save the document and close it
        document.save("prescription.pdf"); //Todo: position from property file
        document.close();
        //open file with standard OS application
        Desktop.getDesktop().open(new File("prescription.pdf"));

        //Print file directly from standard printer (NOT SUPPORTED ON OCULUS-LINUX -- should be tested first!!!)
        //Desktop.getDesktop().print(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/prescription.pdf"));
    } catch (COSVisitorException | CantGetPresciptionEntriesException | IOException e) {
        throw e;
    }
}

From source file:au.org.alfred.icu.pdf.services.dischargesummary.pdfservice.java

public String discharge(@WebParam(name = "parameters") String parameters) {

    PDDocument pdf = null;/*  w w w  .j av a  2  s.c o  m*/
    String encodedPdf = "Error";
    //ByteArrayOutputStream output = new ByteArrayOutputStream();
    String pdfName = "Error Could Not Create File";
    try {
        pdf = new PDDocument();
        JSONObject jsonParams = new JSONObject(parameters);

        String title = jsonParams.getString("pmiid");
        String subject = jsonParams.getString("admid");
        String keywords = jsonParams.getString("admid");
        String creator = jsonParams.getString("user");
        String author = jsonParams.getString("user");
        ICUDischargeSummaryFactory.addDocumentInformation(pdf, title, subject, keywords, creator, author);
        pdfName = ICUDischargeSummaryFactory.createContent(pdf, jsonParams.getString("icuid"),
                jsonParams.getString("admid"), jsonParams.getString("pmiid"), jsonParams.getString("user"),
                jsonParams.getString("userid"));

        ICUDischargeSummaryFactory.saveDocument(
                "/opt/glassfish3/glassfish/domains/domain1/applications/ICUDischargeSummaryWeb/pdf_tmp/"
                        + pdfName,
                pdf);
        pdf.close();

    } catch (IOException ex) {
        ex.printStackTrace(System.out);
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    } catch (COSVisitorException ex) {
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    }

    return pdfName;
}

From source file:au.org.alfred.icu.pdf.services.dischargesummary.pdfservice.java

public String dischargeToCerner(@WebParam(name = "parameters") String parameters) {

    PDDocument pdf;/*from   w  w w .  j  a va  2s  . c  o m*/
    String encodedPdf = "Error";
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String pdfName = "Error Could Not Create File";
    try {
        pdf = new PDDocument();
        JSONObject jsonParams = new JSONObject(parameters);

        String title = jsonParams.getString("pmiid");
        String subject = jsonParams.getString("admid");
        String keywords = jsonParams.getString("admid");
        String creator = jsonParams.getString("user");
        String author = jsonParams.getString("user");
        ICUDischargeSummaryFactory.addDocumentInformation(pdf, title, subject, keywords, creator, author);
        pdfName = ICUDischargeSummaryFactory.createContent(pdf, jsonParams.getString("icuid"),
                jsonParams.getString("admid"), jsonParams.getString("pmiid"), jsonParams.getString("user"),
                jsonParams.getString("userid"));

        pdf.save(output);
        String user = "desousami";
        String passwd = "bkdr4ICUm3k";
        String domain = "BAYSIDEHEALTH";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, passwd);
        String path = "smb://alfapps01/apps/ICUApps/CernerDischarge/" + pdfName;
        SmbFile sFile = new SmbFile(path, auth);
        SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
        sfos.write(output.toByteArray());
        output.close();
        pdf.close();

    } catch (IOException ex) {
        ex.printStackTrace(System.out);
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    } catch (COSVisitorException ex) {
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    }

    return pdfName;
}

From source file:au.org.alfred.icu.pdf.services.factories.tests.PDFBoxPrintingFactoryTest.java

@Test
public void canCreatePDF() throws IOException {
    PDDocument pdf = new PDDocument();

    ICUDischargeSummaryFactory.createDischargeSummaryPDF(pdf);

    assertFalse(pdf.getNumberOfPages() == 0);

}

From source file:au.org.alfred.icu.pdf.services.factories.tests.PDFBoxPrintingFactoryTest.java

@Test
public void canSetDocumentInformation() throws IOException {
    PDDocument pdf = new PDDocument();

    String title = "PMIID";
    String subject = "VISIT_NUMBER";
    String keywords = "VISIT_NUMBER";
    String creator = "USER_NAME";
    String author = "USER_NAME";

    ICUDischargeSummaryFactory.addDocumentInformation(pdf, title, subject, keywords, creator, author);

    assertTrue(pdf.getDocumentInformation().getAuthor().equals(author));

}

From source file:au.org.alfred.icu.pdf.services.factories.tests.PDFBoxPrintingFactoryTest.java

@Test
public void canSetPageContent() {
    try {/*www. j  a  v  a 2  s  .  co  m*/
        PDDocument pdf = new PDDocument();
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        String visitNumber = "ALFI1148735";
        String icuVisitNumber = "41604";
        String patientId = "ALF6216718";

        String pdfName = ICUDischargeSummaryFactory.createContent(pdf, icuVisitNumber, visitNumber, patientId,
                "Miguel de Sousa", "760");
        String user = "desousami";
        String domain = "BAYSIDEHEALTH";
        String passwd = "bkdr4ICUm3k";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, passwd);
        String path = "smb://alfapps01/apps/ICUApps/CernerDischarge/" + pdfName;
        System.out.println(path);
        //SmbFile sFile = new SmbFile(path, auth);
        //SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
        //pdf.save(output);
        //sfos.write(output.toByteArray());
        //output.close();

        ICUDischargeSummaryFactory.saveDocument("/home/miguel/pdftest/" + pdfName, pdf);

        assertTrue(pdf.getNumberOfPages() > 0);
        pdf.close();
    } catch (COSVisitorException ex) {
        ex.printStackTrace(System.out);
        Logger.getLogger(PDFBoxPrintingFactoryTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
        Logger.getLogger(PDFBoxPrintingFactoryTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:barcode.printer.view.PrintForm.java

License:Apache License

public void buttonPrintAction() {
    if (listModel.isEmpty()) {
        return;//from  w  w w.  j a v  a2s.  c o m
    }
    try (PDDocument document = new PDDocument()) {

        PDPage page = new PDPage();

        document.addPage(page);

        PDFont font = PDType1Font.COURIER_BOLD;

        float fontSize = 10f;
        float fontWidth = font.getStringWidth("W") / 1000 * fontSize;
        float fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
        float startXOrigin = fontWidth * 0.3f;
        float startYOrigin = page.findMediaBox().getUpperRightY();
        float startX = startXOrigin;
        float startY;

        try (PDPageContentStream cs = new PDPageContentStream(document, page)) {

            int bcWidth = 80;
            int bcHeight = 20;

            int row = 1;

            for (int idx = 0; idx < listModel.getSize(); idx++) {
                BitMatrix bitMatrix;
                String strBarCode = listModel.get(idx);
                switch (comboCode.getSelectedIndex()) {
                case 0:
                    bitMatrix = new CodaBarWriter().encode(strBarCode, BarcodeFormat.CODABAR, bcWidth,
                            bcHeight);
                    break;
                case 1:
                    bitMatrix = new Code128Writer().encode(strBarCode, BarcodeFormat.CODE_128, bcWidth,
                            bcHeight);
                    break;
                case 2:
                    bitMatrix = new Code39Writer().encode(strBarCode, BarcodeFormat.CODE_39, bcWidth, bcHeight);
                    break;
                case 3:
                    bitMatrix = new EAN13Writer().encode(strBarCode, BarcodeFormat.EAN_13, bcWidth, bcHeight);
                    break;
                case 4:
                    bitMatrix = new EAN8Writer().encode(strBarCode, BarcodeFormat.EAN_8, bcWidth, bcHeight);
                    break;
                case 5:
                    bitMatrix = new ITFWriter().encode(strBarCode, BarcodeFormat.ITF, bcWidth, bcHeight);
                    break;
                default:
                    bitMatrix = new CodaBarWriter().encode(strBarCode, BarcodeFormat.CODABAR, bcWidth,
                            bcHeight);
                    break;
                }

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                PDXObjectImage pdxoi = new PDJpeg(document, bufferedImage);

                startY = startYOrigin - (bitMatrix.getHeight() * row * 1.6f);
                row++;

                cs.beginText();
                cs.setFont(font, fontSize);
                cs.moveTextPositionByAmount(startX + fontWidth, startY + fontHeight);
                cs.drawString(strBarCode);
                cs.endText();
                cs.drawImage(pdxoi, startX, startY - fontHeight);
            }

        }

        document.silentPrint();

        listModel.clear();
        buttonDelete.setEnabled(false);

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
        LOGGER.log(Level.SEVERE, null, ex);
    }

}

From source file:blankpdf.BlankPDF.java

public void TestePDF() {
    String fileName = "Sparta.pdf"; // name of our file

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();

    doc.addPage(page);/*from   w w  w  .  ja va  2 s  . co  m*/
    PDImageXObject imagem;
    PDPageContentStream content;
    try {
        content = new PDPageContentStream(doc, page);

        //OBSERVAO IMPORTANTE --
        //Para funcionar sem tratamento de string criar o projeto em pasta sem caracteres
        //especiais nem ESPAO EM BRANCO
        imagem = PDImageXObject.createFromFile(getClass().getResource("sparta.png").getPath(), doc);
        ///Users/marcelosiedler/Google%20Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/silviosantos.jpg
        //imagem = PDImageXObject.createFromFile("/Users/marcelosiedler/Google Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/sparta.png", doc);

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 26);
        content.newLineAtOffset(10, 750);
        content.showText("Gincana IFSUL2");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 16);
        content.newLineAtOffset(80, 700);
        content.showText("Turma : ");
        content.endText();

        content.drawImage(imagem, 75, 500);

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("Arquivo criado em : " + System.getProperty("user.dir"));

    } catch (Exception e) {

        System.out.println(e.getMessage());

    }

}

From source file:br.com.techne.gluonsoft.pdfgenerator.PDFGenerator.java

License:Apache License

/**
 * Create a new PDF document//from w  w  w. j a  va2 s .com
 * @param filename File name.
 */
public void createDocument(String fileName) {
    PDDocument doc = new PDDocument();

    this.setPdfFileName(fileName);
    this.setPdfDocument(doc);
}

From source file:Bulletin.Bulletin2.java

public Bulletin2(Periode p, int scale, dataBase myDB) {
    this.document = new PDDocument();
    this.p = p;//from  w  w  w  . java  2  s.c om
    this.textScale = (float) (1.0 + 0.01 * scale);
    this.rowHeight *= textScale;
    this.myDB = myDB;
}