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:domain.mediator.PDFGeneration.java

public static void printTodayPDF(List<Logbook> logbookList, Driver driver, Load load,
        GPSLocation currentLocation) throws IOException {

    Table logbookTable = LogbookList.drawLogbookTable(logbookList);

    File saveFile = new File("todayTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);/*from   www.  j  a v  a  2  s .  c  o  m*/
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, logbookTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:domain.mediator.PDFGeneration.java

public static void printRecapPDF(List<Recap> recapList, Driver driver, Load load, GPSLocation currentLocation)
        throws IOException {

    Table recapTable = RecapList.drawRecapTable(recapList);

    File saveFile = new File("recapTable.pdf");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);/*from w  w  w .j  a  v a 2s  . com*/
    PDPageContentStream pageContentStream = new PDPageContentStream(document, page);

    float contentPositionX = 40;
    float contentPositionY = page.getMediaBox().getHeight() - 50;

    PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load,
            currentLocation, recapTable);

    pageContentStream.close();

    document.save(saveFile);
    document.close();
    PDFGeneration.openFile(saveFile);
}

From source file:dpfmanager.shell.modules.report.util.ReportPDF.java

License:Open Source License

/**
 * Parse a global report to PDF format.//from  ww w. j av a  2 s  . co m
 *
 * @param pdffile the file name.
 * @param gr      the global report.
 */
public void parseGlobal(String pdffile, GlobalReport gr) {
    try {
        PDFParams pdfParams = new PDFParams();
        pdfParams.init(PDPage.PAGE_SIZE_A4);

        PDFont font = PDType1Font.HELVETICA_BOLD;
        int pos_x = 200;
        pdfParams.y = 700;
        int font_size = 18;
        // Logo
        PDXObjectImage ximage = new PDJpeg(pdfParams.getDocument(),
                getFileStreamFromResources("images/logo.jpg"));
        float scale = 3;
        pdfParams.getContentStream().drawXObject(ximage, pos_x, pdfParams.y, 645 / scale, 300 / scale);

        // Report Title
        pdfParams.y -= 30;
        pdfParams = writeText(pdfParams, "MULTIPLE REPORT", pos_x, font, font_size);
        pdfParams.y -= 30;
        font_size = 15;
        pdfParams = writeText(pdfParams, "Processed files: " + gr.getIndividualReports().size(), pos_x, font,
                font_size, Color.cyan);

        // Summary table
        pos_x = 100;
        pdfParams.y -= 15;
        font_size = 8;
        Color col;
        for (String iso : gr.getCheckedIsos()) {
            if (gr.getIsos().contains(iso) || gr.getReportsOk(iso) == gr.getReportsCount()) {
                String name = ImplementationCheckerLoader.getIsoName(iso);
                pdfParams.y -= 15;
                col = gr.getReportsOk(iso) == gr.getReportsCount() ? Color.green : Color.red;
                pdfParams = writeText(pdfParams, gr.getReportsOk(iso) + " files conforms to " + name, pos_x,
                        font, font_size, col);
            }
        }

        // Pie chart
        pdfParams.y += 10;
        if (pdfParams.y > 565)
            pdfParams.y = 565;
        pos_x += 200;
        int graph_size = 40;
        BufferedImage image = new BufferedImage(graph_size * 10, graph_size * 10, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        Double doub = (double) gr.getAllReportsOk() / gr.getReportsCount();
        double extent = 360d * doub;
        g2d.setColor(Color.green);
        g2d.fill(new Arc2D.Double(0, 0, graph_size * 10, graph_size * 10, 90, 360, Arc2D.PIE));
        g2d.setColor(Color.red);
        g2d.fill(new Arc2D.Double(0, 0, graph_size * 10, graph_size * 10, 90, 360 - extent, Arc2D.PIE));
        ximage = new PDJpeg(pdfParams.getDocument(), image);
        pdfParams.getContentStream().drawXObject(ximage, pos_x, pdfParams.y, graph_size, graph_size);
        pdfParams.y += graph_size - 10;
        font_size = 7;
        pdfParams = writeText(pdfParams, gr.getAllReportsOk() + " passed", pos_x + 50, font, font_size,
                Color.green);
        pdfParams.y -= 10;
        pdfParams = writeText(pdfParams, gr.getAllReportsKo() + " failed", pos_x + 50, font, font_size,
                Color.red);
        pdfParams.y -= 10;
        pdfParams = writeText(pdfParams, "Global score " + (int) (doub * 100) + "%", pos_x + 50, font,
                font_size, Color.black);

        /**
         * Individual Tiff images list
         */
        pos_x = 100;
        pdfParams.y -= 50;
        for (IndividualReport ir : gr.getIndividualReports()) {
            int image_height = 65;
            int image_width = 100;

            // Draw image
            String imgPath = pdffile + "img.jpg";
            int ids = 0;
            while (new File(imgPath).exists())
                imgPath = pdffile + "img" + ids++ + ".jpg";
            boolean check = tiff2Jpg(ir.getFilePath(), imgPath);
            BufferedImage bimg;
            if (!check) {
                bimg = ImageIO.read(getFileStreamFromResources("html/img/noise.jpg"));
            } else {
                bimg = ImageIO.read(new File(imgPath));
            }
            image_width = image_height * bimg.getWidth() / bimg.getHeight();
            if (image_width > 100) {
                image_width = 100;
                image_height = image_width * bimg.getHeight() / bimg.getWidth();
            }

            // Check if we need new page before draw image
            int maxHeight = getMaxHeight(ir, image_height);
            if (newPageNeeded(pdfParams.y - maxHeight)) {
                pdfParams.setContentStream(newPage(pdfParams.getContentStream(), pdfParams.getDocument()));
                pdfParams.y = init_posy;
            }

            int initialy = pdfParams.y;
            int initialx = 100;

            pdfParams.y -= maxHeight;
            int maxy = pdfParams.y;

            ximage = new PDJpeg(pdfParams.getDocument(), bimg);
            pdfParams.getContentStream().drawXObject(ximage, pos_x, pdfParams.y, image_width, image_height);
            if (check)
                new File(imgPath).delete();

            // Values
            image_width = initialx;
            pdfParams.y = initialy;
            if (maxHeight == 65) {
                pdfParams.y -= 10;
            }
            pdfParams = writeText(pdfParams, ir.getFileName(), pos_x + image_width + 10, font, font_size,
                    Color.gray);
            font_size = 6;
            pdfParams.y -= 10;
            pdfParams = writeText(pdfParams, "Conformance Checker", pos_x + image_width + 10, font, font_size,
                    Color.black);
            pdfParams.getContentStream().drawLine(pos_x + image_width + 10, pdfParams.y - 5, image_width + 150,
                    pdfParams.y - 5);
            pdfParams.y -= 2;

            // Isos table
            for (String iso : ir.getCheckedIsos()) {
                if (ir.hasValidation(iso) || ir.getNErrors(iso) == 0) {
                    String name = ImplementationCheckerLoader.getIsoName(iso);
                    pdfParams.y -= 10;
                    pdfParams = writeText(pdfParams, name, pos_x + image_width + 10, font, font_size,
                            Color.black);
                    pdfParams = writeText(pdfParams, ir.getNErrors(iso) + " errors", pos_x + image_width + 110,
                            font, font_size, ir.getNErrors(iso) > 0 ? Color.red : Color.black);
                    pdfParams = writeText(pdfParams, ir.getNWarnings(iso) + " warnings",
                            pos_x + image_width + 140, font, font_size,
                            ir.getNWarnings(iso) > 0 ? Color.orange : Color.black);
                }
            }
            if (pdfParams.y < maxy)
                maxy = pdfParams.y;

            // Chart
            pdfParams.y = initialy;
            pdfParams.y -= 10;
            pdfParams.y -= 10;
            graph_size = 25;
            image = new BufferedImage(graph_size * 10, graph_size * 10, BufferedImage.TYPE_INT_ARGB);
            g2d = image.createGraphics();
            doub = (double) ir.calculatePercent();
            extent = 360d * doub / 100.0;
            g2d.setColor(Color.gray);
            g2d.fill(new Arc2D.Double(0, 0, graph_size * 10, graph_size * 10, 90, 360, Arc2D.PIE));
            g2d.setColor(Color.red);
            g2d.fill(new Arc2D.Double(0, 0, graph_size * 10, graph_size * 10, 90, 360 - extent, Arc2D.PIE));
            ximage = new PDJpeg(pdfParams.getDocument(), image);
            pdfParams.getContentStream().drawXObject(ximage, pos_x + image_width + 180,
                    pdfParams.y - graph_size, graph_size, graph_size);
            pdfParams.y += graph_size - 10;
            if (doub < 100) {
                pdfParams.y = pdfParams.y - 10 - graph_size / 2;
                pdfParams = writeText(pdfParams, "Failed", pos_x + image_width + 180 + graph_size + 10, font,
                        font_size, Color.red);
            }
            pdfParams.y = pdfParams.y - 10 - graph_size / 2;
            pdfParams = writeText(pdfParams, "Score " + doub + "%", pos_x + image_width + 180 + graph_size + 10,
                    font, font_size, Color.gray);
            if (pdfParams.y < maxy)
                maxy = pdfParams.y;

            pdfParams.y = maxy - 10;
        }

        // Full individual reports
        ArrayList<PDDocument> toClose = new ArrayList<PDDocument>();
        for (IndividualReport ir : gr.getIndividualReports()) {

            if (!ir.containsData())
                continue;
            PDDocument doc = null;
            if (ir.getPDF() != null)
                doc = ir.getPDF();
            else if (ir.getPDFDocument() != null)
                doc = PDDocument.load(ir.getPDFDocument());
            if (doc != null) {
                List<PDPage> l = doc.getDocumentCatalog().getAllPages();
                for (PDPage pag : l) {
                    pdfParams.getDocument().addPage(pag);
                }
                toClose.add(doc);
            }
        }

        pdfParams.getContentStream().close();

        pdfParams.getDocument().save(pdffile);
        pdfParams.getDocument().close();

        for (PDDocument doc : toClose) {
            doc.close();
        }
    } catch (Exception tfe) {
        context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage("Exception in ReportPDF", tfe));
    }
}

From source file:dtlgenerator.myDataReader.java

public void PdfGenerator(String pdfFileNameBase, List<String> cycles) throws IOException, COSVisitorException {
    GlobalVar.dirMake(new File(pdfFileNameBase)); //create a folder with the same name

    int rowCount = 0;
    int pageCount = 1;
    PDPage page; //default size PAGE_SIZE_A4
    PDPageContentStream stream;// w w w.ja  va2  s. com
    //page.setRotation(90); //counterclock wise rotate 90 degree  ////left hand rule

    //        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
    String lastUpdate = null;
    String lastCycle = null;
    System.out.println("DTL_DATA keyset:" + DTL_DATA.keySet());
    System.out.println("Cycles empty? " + cycles.isEmpty());
    System.out.println(cycles);
    for (String updateDate : DTL_DATA.keySet()) {
        Map<String, List<String>> thisDTData = DTL_DATA.get(updateDate);
        lastUpdate = updateDate;
        System.out.println("thisDT_DATA keyset:" + thisDTData.keySet());
        for (String cycle : thisDTData.keySet()) {
            if (cycles.isEmpty() || cycles.contains(cycle)) {
                PDDocument pdf = new PDDocument();
                lastCycle = cycle;
                List<String> thisCycle = thisDTData.get(cycle);
                pageCount = 1; // new cycle, restart page num
                page = new PDPage(); //page break
                stream = new PDPageContentStream(pdf, page, true, false);
                stream.beginText();
                page.setRotation(PAGE_ROT_DEGREE);
                //stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                addBigFontUpdateNumberAndCycle(updateDate, cycle, stream);
                stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                // stream.setFont(PDType1Font.
                int thisCycleRowCount = 0;
                for (String row : thisCycle) {
                    if (thisCycleRowCount > MAX_NUM_TRANS) {
                        //close the current page
                        setupFootNote(stream, pageCount, cycle, updateDate);
                        pageCount++;
                        stream.endText();
                        stream.close();
                        pdf.addPage(page);

                        // start a new page
                        page = new PDPage();
                        stream = new PDPageContentStream(pdf, page, true, false);
                        page.setRotation(PAGE_ROT_DEGREE);
                        stream.beginText();
                        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                        thisCycleRowCount = 0;
                    }
                    stream.setTextRotation(TEXT_ROT_RAD, TRANS_X + thisCycleRowCount * INVERVAL_X, TRANS_Y);
                    stream.drawString(row);
                    thisCycleRowCount++;
                    //System.out.println("Update:" + updateDate + " Cycle: " + cycle + " " + row);
                }
                setupFootNote(stream, pageCount, lastCycle, lastUpdate);
                stream.endText();
                stream.close();
                pdf.addPage(page);
                String pdfFileName = pdfFileNameBase + "\\DTL UPDT " + updateDate + " " + cycle + ".pdf";

                pdf.save(pdfFileName);
                pdf.close();
            }
        }
    }

    // pdf.save(pdfFileName);        
    // pdf.close();      
}

From source file:editorframework.pdfbox.testes.MyPDFBox.java

private void init() {
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    try {//from  ww w  . ja  v  a  2 s  .c o m
        final PDDocument doc = PDDocument.load(new File("./simple.pdf"));
        List<PDPage> allPages = doc.getDocumentCatalog().getAllPages();
        PDPage page = (PDPage) allPages.get(1);
        setPage(page);
        jFrame.setBackground(Color.DARK_GRAY);
        setLayout(new FlowLayout());
        jFrame.add(this);
        jFrame.setBounds(40, 40, getWidth() + 100, getHeight() + 50);
        jFrame.setVisible(true);
        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    doc.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    } catch (IOException e) {
        System.out.println(e.toString());
    }
    //doc.close();
}

From source file:edu.harvard.mcz.precapture.encoder.PrintingUtility.java

License:Open Source License

/**
 * Send the generated PDF file to a printer.  (file to print is from LabelEncoder.getPrintFile().
 * //from   w w w .java2  s  . c  o m
 * @param printDefinition Used to find paper size
 * @param paperWidthPoints
 * @param paperHeightPoints
 * @throws PrintFailedException if printing fails for any reason.
 */
public static void sendPDFToPrinter(LabelDefinitionType printDefinition, int paperWidthPoints,
        int paperHeightPoints) throws PrintFailedException {
    try {

        // send generated PDF to printer.

        FileInputStream pdfInputStream = new FileInputStream(PreCaptureSingleton.getInstance().getProperties()
                .getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE));

        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.PDF;

        // No printers listed... Don't Try autosense instead of PDF
        // DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        // Ends up listing printers that can't take the PDF,
        // Need instead to fail over to using a pdf printing library 
        // and having the pdf printing library pull up the printer dialog.

        Doc myDoc = new SimpleDoc(pdfInputStream, psInFormat, null);
        PrintRequestAttributeSet atset = new HashPrintRequestAttributeSet();
        atset.add(new Copies(1));
        // Set paper size
        if (paperWidthPoints == 612 && paperHeightPoints == 792) {
            atset.add(MediaSizeName.NA_LETTER);
        } else {
            float x = printDefinition.getPaperWidth();
            float y = printDefinition.getPaperHeight();
            if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) {
                MediaSizeName mediaSizeName = MediaSize.findMedia(x, y, Size2DSyntax.INCH);
                if (mediaSizeName == null) {
                    // TODO: Handle non-standard paper sizes.  The following doesn't provide
                    // what is needed.
                    atset.add(new MediaPrintableArea(0, 0, x, y, MediaPrintableArea.INCH));
                } else {
                    atset.add(mediaSizeName);
                }
            }
            if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) {
                x = x * 10f;
                y = y * 10f;
                atset.add(MediaSize.findMedia(x, y, Size2DSyntax.INCH));
            }
            if (printDefinition.getUnits().toString().toLowerCase().equals("points")) {
                x = x / 72f;
                y = y / 72f;
                atset.add(MediaSize.findMedia(x, y, Size2DSyntax.INCH));
            }
        }
        atset.add(Sides.ONE_SIDED);
        PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, atset);
        log.debug("Number of matching printing services =  " + services.length);
        boolean printed = false;
        if (services.length == 0) {
            log.debug("No PDF printing services found.");
            log.error("Failing over to print using a pdf printing library");

            try {
                pdfInputStream.close();

                pdfInputStream = new FileInputStream(PreCaptureSingleton.getInstance().getProperties()
                        .getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE));

                // trying pdfbox instead of pdf-renderer
                PDDocument pdfDocument = PDDocument.load(pdfInputStream);
                pdfDocument.print();
                pdfDocument.close();
                printed = true;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            log.debug("Available printing services " + services.length);
            for (int i = 0; i < services.length; i++) {
                log.debug(services[i].getName());
            }
            Object selectedService = JOptionPane.showInputDialog(null, "Send labels to which printer?", "Input",
                    JOptionPane.INFORMATION_MESSAGE, null, services, services[0]);
            if (selectedService != null) {
                DocPrintJob job = ((PrintService) selectedService).createPrintJob();
                log.debug("Printing to " + ((PrintService) selectedService).getName());
                try {
                    job.print(myDoc, atset);
                    printed = true;
                } catch (PrintException pe) {
                    log.error("Printing Error: " + pe.getMessage());
                    if (pe.getClass().getName().equals("sun.print.PrintJobFlavorException")) {

                        log.error("Failing over to print using a pdf printing library");

                        try {
                            pdfInputStream.close();

                            pdfInputStream = new FileInputStream(
                                    PreCaptureSingleton.getInstance().getProperties().getProperties()
                                            .getProperty(PreCaptureProperties.KEY_LABELPRINTFILE));

                            // Send PDF to printer using PDFBox PDF printing support.
                            PDDocument pdfDocument = PDDocument.load(pdfInputStream);
                            pdfDocument.print();
                            pdfDocument.close();
                            printed = true;
                            // Note, can't get pdf-renderer to print without re-scaling and shrinking the document.

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
            pdfInputStream.close();
        }
        if (!printed) {
            log.error("No available printing services");
            throw new PrintFailedException("Unable to locate or use a printer, print the file '"
                    + PreCaptureSingleton.getInstance().getProperties().getProperties()
                            .getProperty(PreCaptureProperties.KEY_LABELPRINTFILE)
                    + "'");
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage());
        throw new PrintFailedException("Unable to find PDF file to print " + e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage());
        if (e != null && e.getCause() != null) {
            log.error(e.getCause().getMessage());
        }
        throw new PrintFailedException("No labels to print." + e.getMessage());
    }
}

From source file:edu.ist.psu.sagnik.research.pdfbox2playground.javatest.DrawPrintTextLocations.java

License:Apache License

/**
 * This will print the documents data./* w  w w . j  a  v  a  2s  .com*/
 *
 * @param args The command line arguments.
 *
 * @throws IOException If there is an error parsing the document.
 */
public static void main(String[] args) throws IOException {

    PDDocument document = null;
    try {
        document = PDDocument.load(new File(new DataLocation().pdLoc));

        DrawPrintTextLocations stripper = new DrawPrintTextLocations(document, new DataLocation().pdLoc);
        stripper.setSortByPosition(true);

        for (int page = 0; page < document.getNumberOfPages(); ++page) {
            stripper.stripPage(page);
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }

}

From source file:edu.ist.psu.sagnik.research.pdfbox2playground.javatest.ExtractImages.java

License:Apache License

private void extract(String pdfFile, String password) throws IOException {
    PDDocument document = null;
    try {//  w  ww.j a v  a2s  .  co m
        document = PDDocument.load(new File(pdfFile), password);
        AccessPermission ap = document.getCurrentAccessPermission();
        if (!ap.canExtractContent()) {
            throw new IOException("You do not have permission to extract images");
        }

        for (int i = 0; i < document.getNumberOfPages(); i++) // todo: ITERATOR would be much better
        {
            PDPage page = document.getPage(i);
            ImageGraphicsEngine extractor = new ImageGraphicsEngine(page);
            extractor.run();
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:edu.uci.ics.crawler4j.parser.Parser.java

License:Apache License

private void treatPDFContentType(Page page) throws IOException {
    PDDocument doc = PDDocument.load(new ByteArrayInputStream(page.getContentData()));
    page.setParseData(new PDFParseData(pdfTextStripper.getText(doc)));
    doc.close();
}

From source file:edu.ur.ir.index.DefaultPdfTextExtractor.java

License:Apache License

/**
 * Close the PD document/*from   w w w.j ava2  s  .com*/
 * 
 * @param cosDoc
 */
private void closePDDocument(PDDocument pdDoc) {
    if (pdDoc != null) {
        try {
            pdDoc.close();
            pdDoc = null;
        } catch (Exception e) {
            log.error("could not close PDDocument", e);
            pdDoc = null;
        }
    }
}