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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

Usage

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

License:Open Source License

/**
 * <h3>$printPrescription</h3>
 * <p/>// w  w  w.  j  a va 2s  . c  o  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;
    String encodedPdf = "Error";
    //ByteArrayOutputStream output = new ByteArrayOutputStream();
    String pdfName = "Error Could Not Create File";
    try {//from   ww w  . j a v  a2  s.  c o m
        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;
    String encodedPdf = "Error";
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String pdfName = "Error Could Not Create File";
    try {//from   w w w  . ja  v  a2 s . c  om
        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.ICUDischargeSummaryFactory.java

public static String loadDischargePDF(InputStream file) throws IOException {
    String pdf_str = null;/*from ww  w  .j a v  a 2s  .co m*/
    PDDocument doc = PDDocument.load(file);
    int pages = doc.getNumberOfPages();
    //System.out.println(pages);
    PDFTextStripper txt = new PDFTextStripper();
    txt.setStartPage(1);
    txt.setEndPage(1);
    pdf_str = txt.getText(doc);
    /*for(Iterator<COSObject> pdfItr = doc.getDocument().getObjects().iterator(); pdfItr.hasNext();)
     {
     COSObject inner = pdfItr.next();
            
            
     }*/
    //pdf_str = doc.getDocument().getObjects();
    doc.close();
    return pdf_str;
}

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

@Test
public void canSetPageContent() {
    try {/*from   www .j  a  va2  s. c o 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: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 ww .j  av a  2 s  . c om
    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.intercomex.pdfreader.PdrFeaderWS.java

private String getPdf(Blob pdf) throws SQLException, IOException {
    String text = null;/*from ww w.  ja va  2 s.co m*/
    PDDocument document = PDDocument.load(pdf.getBinaryStream());
    PDFTextStripper stripper = new PDFTextStripper("UTF-16");
    text = stripper.getText(document);
    document.close();
    return text;
}

From source file:Bulletin.test.java

public static void test2() {
    try {//from   w  w  w . j a v a  2  s .  c om
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        PDPageContentStream cos = null;
        try {
            cos = new PDPageContentStream(document, page);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }

        float X = 501.4f;
        float Y = 556.0f;
        //            String text = "HALLO";
        //            String text = "HALLO#HOE#GAAT#HET";
        //            String text = "HALLO#HOE#GAAT";
        String text = "Non atteints";
        int rh = 10;

        cos.moveTo(X, Y - 50);
        cos.lineTo(X, Y + 50);
        cos.stroke();
        cos.moveTo(X - 50, Y);
        cos.lineTo(X + 50, Y);
        cos.stroke();

        cos.beginText();
        cos.setFont(PDType1Font.HELVETICA, 6);
        float dtw = 0.5f * getTextWidth(PDType1Font.HELVETICA, text, 6);
        float dth = 0.0f * getFontHeight(PDType1Font.HELVETICA, 6);
        int nbLines = text.split("#").length;

        Y += 0.5f * (nbLines - 1) * rh;

        for (String line : text.split("#")) {
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(Math.toRadians(0), 0, 0));
            M.concatenate(Matrix.getTranslateInstance(-dtw, -dth));
            cos.setTextMatrix(M);
            cos.showText(line);
            Y -= rh;
        }
        cos.close();
        document.addPage(page);
        document.save("/tmp/test.pdf");
        document.close();

    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ca.uqac.lif.labpal.FileHelper.java

License:Open Source License

/**
 * Merges multiple PDF files into a single file
 * @param dest The destination filename/*  ww w  . j a v a 2  s . com*/
 * @param paths The input files
 * @return The array of bytes containing the merged PDF
 */
@SuppressWarnings("deprecation")
public static byte[] mergePdf(String dest, String... paths) {
    try {
        ByteArrayOutputStream out = null;
        List<File> lst = new ArrayList<File>();
        List<PDDocument> lstPDD = new ArrayList<PDDocument>();
        for (String path : paths) {
            File file1 = new File(path);

            lstPDD.add(PDDocument.load(file1));
            lst.add(file1);
        }
        PDFMergerUtility PDFmerger = new PDFMergerUtility();

        // Setting the destination file
        PDFmerger.setDestinationFileName(dest);
        for (File file : lst) {
            // adding the source files
            PDFmerger.addSource(file);

        }
        // Merging the two documents
        PDFmerger.mergeDocuments();

        for (PDDocument pdd : lstPDD) {
            pdd.close();
        }

        PDDocument pdf = PDDocument.load(new File(dest));

        out = new ByteArrayOutputStream();

        pdf.save(out);
        byte[] data = out.toByteArray();
        pdf.close();
        return data;
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage());
    }
    return null;
}

From source file:casmi.Applet.java

License:Open Source License

@Override
public void drawWithGraphics(Graphics g) {
    setGLParam(g.getGL());/*from  w ww.j av  a2  s .com*/

    drawObjects(g);

    updateObjects();

    // Calculate real fps.
    {
        frame++;
        long now = System.currentTimeMillis();
        long elapse = now - baseTime;
        if (1000 < elapse) {
            workingFPS = frame * 1000.0 / elapse;
            baseTime = now;
            frame = 0;
        }
    }

    // capture image
    if (saveImageFlag) {
        saveImageFlag = false;

        try {
            switch (imageType) {
            case JPG:
            case PNG:
            case BMP:
            case GIF:
            default:
                Screenshot.writeToFile(new File(saveFile), width, height, !saveBackground);
                break;
            case PDF: {
                BufferedImage bi = Screenshot.readToBufferedImage(width, height, !saveBackground);
                PDDocument doc = new PDDocument();
                PDRectangle rect = new PDRectangle(width, height);
                PDPage page = new PDPage(rect);
                doc.addPage(page);
                PDXObjectImage ximage = new PDJpeg(doc, bi);
                PDPageContentStream contentStream = new PDPageContentStream(doc, page);
                contentStream.drawImage(ximage, 0, 0);
                contentStream.close();
                doc.save(saveFile);
                doc.close();
                break;
            }
            }
        } catch (GLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (COSVisitorException e) {
            e.printStackTrace();
        }
    }
}