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

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

Introduction

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

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

From source file:compressor.Compressor.java

void extract_images(String src, String dest, String img_name) throws IOException {
    PDDocument document = null;//  w w  w . j  ava  2s  . c om
    try {
        document = PDDocument.load(src);
    } catch (IOException ex) {
        System.out.println("" + ex);
    }
    List pages = document.getDocumentCatalog().getAllPages();
    Iterator iter = pages.iterator();
    int i = 1;
    String name = null;

    File file = new File(dest + "img");
    if (!file.exists()) {
        if (file.mkdir()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }
    dest = dest + "img/";

    while (iter.hasNext()) {
        PDPage page = (PDPage) iter.next();
        PDResources resources = page.getResources();
        Map pageImages = resources.getImages();
        if (pageImages != null) {
            Iterator imageIter = pageImages.keySet().iterator();
            while (imageIter.hasNext()) {
                String key = (String) imageIter.next();
                PDXObjectImage image = (PDXObjectImage) pageImages.get(key);

                image.write2file(dest + img_name + i);
                i++;
            }
        }
    }
    document.close();
}

From source file:Control.MyiReportVisor.java

/**
 * si se desea imprimir solo una hoja, se llama al objeto "printr"
 * si se desea imprimir hoja + copia, se llama al objeto "pages"
 *///  www .  ja va 2  s .  c  om
public void exportarAPdfConCopia() throws IOException {
    try {
        //EXPORTANDO PDF
        System.out.println("Exportando a pdf");
        final JRPdfExporter exp = new JRPdfExporter();
        exp.setParameter(JRExporterParameter.JASPER_PRINT_LIST, pages);
        exp.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exp.setParameter(JRExporterParameter.OUTPUT_FILE,
                new File("D:\\pdfGenerados\\" + nombreArchivo + ".pdf"));
        exp.exportReport();
        PrinterJob job = PrinterJob.getPrinterJob();
        PDDocument pdc = PDDocument.load(new File("D:\\pdfGenerados\\" + nombreArchivo + ".pdf"));
        System.out.println("" + pdc.getNumberOfPages());
        job.setPageable(new PDFPageable(pdc));
        try {
            job.print();
        } catch (PrinterException ex) {
            Logger.getLogger(MyiReportVisor.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Mostrando PDF");
        //Abriendo PDF
        //Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler "+"D:\\pdfGenerados\\" + nombreArchivo + ".pdf");
    } catch (JRException ex) {
        ex.printStackTrace();
    }
}

From source file:Controller.Receipt.Controller_FXML_Receipt.java

private void printPDF(String fileName) throws IOException, PrinterException {

    //To change body of generated methods, choose Tools | Templates.
    PrinterJob job = PrinterJob.getPrinterJob();
    javax.print.PrintService printer = null;
    if (job.printDialog()) {
        printer = (javax.print.PrintService) job.getPrintService();
    } else {//from   ww  w .  j  a  v  a2  s  . c  om
        System.out.println("No printer found");
    }

    job.setPrintService(printer);
    PDDocument doc = PDDocument.load(fileName);
    doc.silentPrint(job);
}

From source file:converter.PDFPac.java

/**
 * vrati text z pdf//from  w w w.  j a  va2s  .co  m
 *
 * @param url
 * @return
 */
private String getTextFromPDF(String url) {
    String text = "";
    try {
        PDDocument pdDoc = PDDocument.load(new File(url));
        PDFTextStripper pdfStripper = new PDFTextStripper();
        text = pdfStripper.getText(pdDoc);
        pdDoc.close();

    } catch (IOException ex) {
        logger.warning("PDFPac soubor nebyl nalezen " + url + "chyba " + ex);
    }
    return text;
}

From source file:correccioncolorpdfs.CorrectorColorUI.java

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

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

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

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

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

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

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

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

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

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

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

From source file:cr.ac.siua.tec.utils.impl.AssistancePDFGenerator.java

License:Open Source License

/**
 * Fills the PDF file (asistente.pdf) with the ticket values and returns base64 encoded string.
 *///from   w  ww .j  a  v a 2 s.co m
@Override
public String generate(HashMap<String, String> formValues) {
    String originalPdf = PDFGenerator.RESOURCES_PATH + "asistente.pdf";
    try {
        PDDocument _pdfDocument = PDDocument.load(originalPdf);
        PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        //Set some fields manually.
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        if (month > 10 || month < 5)
            acroForm.getField("Semestre").setValue("PRIMER");
        else
            acroForm.getField("Semestre").setValue("SEGUNDO");

        if (month > 10 && acroForm.getField("Semestre").getValue().equals("PRIMER"))
            year++;

        acroForm.getField("Ao").setValue(String.valueOf(year));
        formValues.remove("Queue");
        acroForm.getField(formValues.get("Banco")).setValue("x");
        formValues.remove("Banco");
        acroForm.getField(formValues.get("Tipo de asistencia")).setValue("x");
        formValues.remove("Tipo de asistencia");

        //Iterates through remaining custom fields.
        for (Map.Entry<String, String> entry : formValues.entrySet()) {
            acroForm.getField(entry.getKey()).setValue(entry.getValue());
        }
        return encodePDF(_pdfDocument);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Excepcin al llenar el PDF.");
        return null;
    }
}

From source file:cr.ac.siua.tec.utils.impl.CEInclusionPDFGenerator.java

License:Open Source License

/**
 * Fills the PDF file (inclusion.pdf) with the ticket values and returns base64 encoded string.
 *///  w  w w . jav  a 2s.  c  o  m
@Override
public String generate(HashMap<String, String> formValues) {
    String originalPdf = PDFGenerator.RESOURCES_PATH + "inclusion.pdf";
    try {
        PDDocument _pdfDocument = PDDocument.load(originalPdf);
        PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();
        formValues.remove("Queue");
        formValues.remove("Justificacin");

        //Set some fields manually.
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        if (month > 10 || month < 5)
            acroForm.getField("Semestre").setValue("I");
        else
            acroForm.getField("Semestre").setValue("II");
        if (month > 10 && acroForm.getField("Semestre").getValue().equals("I"))
            year++;
        acroForm.getField("Ao").setValue(String.valueOf(year));

        //Fills enrolled courses table.
        String enrolledCourses[] = formValues.get("Cursos matriculados").split("\n");
        for (int i = 0; i < enrolledCourses.length; i++) {
            String courseRow[] = enrolledCourses[i].split("-");
            acroForm.getField("Cdigo" + Integer.toString(i)).setValue(courseRow[0]);
            acroForm.getField("Curso" + Integer.toString(i)).setValue(courseRow[1]);
            acroForm.getField("Grupo" + Integer.toString(i)).setValue(courseRow[2]);
        }
        formValues.remove("Cursos matriculados");

        //Iterates through remaining custom fields.
        for (Map.Entry<String, String> entry : formValues.entrySet()) {
            acroForm.getField(entry.getKey()).setValue(entry.getValue());
        }

        return encodePDF(_pdfDocument);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Excepcin al llenar el PDF.");
        return null;
    }
}

From source file:cr.ac.siua.tec.utils.impl.ConstancyPDFGenerator.java

License:Open Source License

/**
 * Fills the PDF file (constancia.pdf) with the ticket values and returns base64 encoded string.
 *///from ww w.  j ava2  s.c o m
@Override
public String generate(HashMap<String, String> formValues) {
    String originalPdf = PDFGenerator.RESOURCES_PATH + "constancia.pdf";
    try {
        PDDocument _pdfDocument = PDDocument.load(originalPdf);
        PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        //Set some fields manually.
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        String date = String.valueOf(day) + " de " + monthsMap.get(month) + " del ao " + String.valueOf(year)
                + ".";
        acroForm.getField("Fecha").setValue(date);

        formValues.remove("Queue");
        formValues.remove("Motivo");
        formValues.remove("Requestors");

        //Iterates through remaining custom fields.
        for (Map.Entry<String, String> entry : formValues.entrySet()) {
            acroForm.getField(entry.getKey()).setValue(entry.getValue());
        }
        return encodePDF(_pdfDocument);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Excepcin al llenar el PDF.");
        return null;
    }
}

From source file:cr.ac.siua.tec.utils.impl.ProficiencyPDFGenerator.java

License:Open Source License

/**
 * Fills the PDF file (suficiencia.pdf) with the ticket values and returns base64 encoded string.
 *//*www  .j a  va  2  s  .c om*/
@Override
public String generate(HashMap<String, String> formValues) {
    String originalPdf = PDFGenerator.RESOURCES_PATH + "suficiencia.pdf";
    try {
        PDDocument _pdfDocument = PDDocument.load(originalPdf);
        PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();
        formValues.remove("Queue");

        //Iterates through all custom field values.
        for (Map.Entry<String, String> entry : formValues.entrySet()) {
            acroForm.getField(entry.getKey()).setValue(entry.getValue());
        }
        return encodePDF(_pdfDocument);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Excepcin al llenar el PDF.");
        return null;
    }
}

From source file:cx.fbn.nevernote.gui.PDFPreview.java

License:Open Source License

public int getPageCount(String filePath) {
    try {//from  ww w  .  ja va  2s  . c o m
        String whichOS = System.getProperty("os.name");
        if (whichOS.contains("Windows")) {
            filePath = filePath.replace("\\", "/");
        }
        PDDocument document = null;
        document = PDDocument.load(filePath);
        return document.getNumberOfPages();
    } catch (Exception e) {
        return 0;
    }

}