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:dpfmanager.shell.modules.report.util.PDFParams.java

License:Open Source License

public void init(PDRectangle pageType) throws IOException {
    document = new PDDocument();
    PDPage page = new PDPage(pageType);
    document.addPage(page);//from w w  w  .j  a  v  a 2 s .  co  m
    contentStream = new PDPageContentStream(document, page);
}

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;/*from  w w  w . j  a  v a2 s  . c  o  m*/
    //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:elaborate.editor.export.pdf.PdfMaker.java

License:Open Source License

public PdfMaker(Project _project, EntityManager _entityManager) {
    this.project = _project;
    this.entityManager = _entityManager;
    if (_project == null) {
        doc = null;/*from  ww  w.  j  a  v  a  2s  . co  m*/

    } else {
        try {
            doc = new PDDocument();

            ProjectService projectService = ProjectService.instance();
            projectService.setEntityManager(entityManager);
            List<ProjectEntry> projectEntriesInOrder = projectService.getProjectEntriesInOrder(project.getId());

            for (ProjectEntry projectEntry : projectEntriesInOrder) {
                PDPage page = new PDPage();
                doc.addPage(page);

                PDFont font = PDType1Font.HELVETICA_BOLD;

                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.beginText();
                content.setFont(font, 12);
                content.drawString(projectEntry.getName());
                for (Transcription transcription : projectEntry.getTranscriptions()) {
                    content.drawString(transcription.getTextLayer());
                    content.drawString(transcription.getBody());
                }

                content.endText();
                content.close();
            }

        } catch (Exception e) {
            System.out.println("Exception");
        }
    }
}

From source file:es.rickyepoderi.pdfimages.Converter.java

License:Open Source License

/**
 * Method that converts the images provides to pdf and writes to the target 
 * path specified./* w  w w . j  a v  a2s.co  m*/
 *
 * @param output The file to write
 * @param bimages The buffered images to put in the pdf
 * @throws IOException Some error generating the PDF
 */
public void images2Pdf(File output, File... files) throws IOException {
    try (PDDocument pdDocument = new PDDocument()) {
        for (File file : files) {
            PDPage page = new PDPage();
            pdDocument.addPage(page);
            try (PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page,
                    PDPageContentStream.AppendMode.APPEND, true, true)) {
                BufferedImage bimage = ImageIO.read(file);
                PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bimage);
                Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()),
                        new Dimension((int) page.getMediaBox().getWidth(),
                                (int) page.getMediaBox().getHeight()));
                pageStream.drawImage(img, 0, 0, scaledDim.width, scaledDim.height);
            }
        }
        pdDocument.save(output);
    }
}

From source file:es.udc.fic.medregatas.util.PDFUtils.java

public static void printPDF(String docName) throws IOException, COSVisitorException {

    createPdfDirectoryIfNotExists();/*  w  ww.  j  a  v a  2 s .c  om*/

    // 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, 12);
    contentStream.moveTextPositionByAmount(100, 700);
    contentStream.drawString("Hello World");
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    // Save the results and ensure that the document is properly closed:
    document.save(PDFS_FOLDER + "/" + docName);
    document.close();
}

From source file:evadoc_splitter.pdfsplitter.java

private void split_report(Rectangle2D programa_area, Rectangle2D periodo_area, Rectangle2D id_area,
        Rectangle2D nombre_area, String type, int numberOfPages) {
    // pages = this.doc

    //crear hash id=>nombre que se guarda en la variable global del programa principal

    try {//from  w w w .ja  va 2s . c  o  m
        //iteracion n - 1
        // Create a new empty document
        PDDocument document_to = new PDDocument();
        //aadir la primera pagina
        PDPage page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(0);
        document_to.addPage(page_from);
        //obtener datos de la primera pagina
        String programa = get_text_by_area(programa_area, page_from, 1);
        String id = get_text_by_area(id_area, page_from, 0);
        String periodo = get_text_by_area(periodo_area, page_from, 2);
        String nombre = get_text_by_area(nombre_area, page_from, 0);

        String path = "";
        String id_to_name;

        File folder;

        //si solo hay una pagina.
        if (numberOfPages == 1) {
            //document_to.save(type+"_"+programa+"_"+id+"_.pdf");
        }

        //TODO: verificar que ninguno es vacio
        //iteracion n, se comprara n con n-1
        //desde la segunda pagina verificar si el id es el mismo y terminar cuando cambie
        for (int i = 1; i < numberOfPages; i++) {
            page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i);
            String id_next = get_text_by_area(id_area, page_from, i);

            //verificar si es hoja vacia

            //verificar que id_next sea igual que id
            if (id_next.equals(id)) {
                //si es igual al anterior aadir la pagina al documento
                document_to.addPage(page_from);
            } else {
                //momento para crear un hash, que relacione id con nombre, 
                //con el fin de referenciar por id y no por nombre.

                set_id_name_hash(id, nombre); //actualizar relacion id => nombre
                // Save the newly created document
                //obtener nombre del id en cuestion:
                id_to_name = this.local_id_to_name.get(id);
                //verificar si esta disponible la informacion sobre la division                
                if (this.has_division) {
                    String division = this.local_programa_to_division.get(programa);
                    //  path = this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+programa+"\\"+id_to_name;
                    path = this.root + "RES_" + periodo + "\\" + division + "\\" + programa + "\\" + id_to_name;
                } else {
                    //  path = this.root+"Resultados_"+this.current_time + "\\" +programa+"\\"+periodo+"\\"+id_to_name;
                    path = this.root + "RES_" + periodo + "\\" + programa + "\\" + id_to_name;
                }
                //create directory if not exist:
                folder = new File(path);
                if (!folder.exists()) {
                    folder.mkdirs();
                }

                document_to.save(path + "\\" + type + ".pdf");

                //Preparacion para la siguiente iteracion 
                //crear un nuevo documento
                document_to = new PDDocument();
                //aadir la pagina encontrada que es diferente a la anterior
                page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i);
                document_to.addPage(page_from);
                //obtener datos de la  pagina
                id = get_text_by_area(id_area, page_from, i);
                while (id == null) {
                    i++;
                    page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i);
                }
                id = get_text_by_area(id_area, page_from, i);
                programa = get_text_by_area(programa_area, page_from, i);
                periodo = get_text_by_area(periodo_area, page_from, i);
                nombre = get_text_by_area(nombre_area, page_from, i);
                set_id_name_hash(id, nombre);
            }

            //aadir el profesor de la ultima pagina

        }

        //:::::::ultima iteracion:::::

        //momento para crear un hash, que relacione id con nombre, 
        //con el fin de referenciar por id y no por nombre.

        id_to_name = this.local_id_to_name.get(id);
        if (this.has_division) {
            String division = this.local_programa_to_division.get(programa);
            // path = this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+programa+"\\"+id_to_name;
            path = this.root + "RES_" + periodo + "\\" + division + "\\" + programa + "\\" + id_to_name;
        } else {
            // path = this.root+"Resultados_"+this.current_time + "\\" +programa+"\\"+periodo+"\\"+id_to_name;
            path = this.root + "RES_" + periodo + "\\" + programa + "\\" + id_to_name;
        }
        folder = new File(path);
        //obtener nombre del id en cuestion:
        if (!folder.exists()) {
            folder.mkdirs();
        }

        document_to.save(path + "\\" + type + ".pdf");

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

    //get periodo

    //get programa

}

From source file:evadoc_splitter.pdfsplitter.java

private void split_report_consolidado_division(Rectangle2D region_div, Rectangle2D region_periodo,
        Rectangle2D region_programa, String type, int numberOfPages) {
    // pages = this.doc

    //crear hash id=>nombre que se guarda en la variable global del programa principal
    Rectangle2D next_region_programa = region_programa;
    try {/*from w w  w .  j  av  a2  s . c  om*/
        //iteracion n - 1
        // Create a new empty document
        PDDocument document_to = new PDDocument();
        //aadir la primera pagina
        PDPage page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(0);
        document_to.addPage(page_from);
        //obtener datos de la primera pagina
        String division = get_text_by_area(region_div, page_from, 1);
        String periodo = get_text_by_area(region_periodo, page_from, 2);
        hash_programs(region_programa, page_from, division);

        //si solo hay una pagina.
        if (numberOfPages == 1) {
            //document_to.save(type+"_"+programa+"_"+id+"_.pdf");
        }
        //TODO: verificar que ninguno es vacio

        //iteracion n, se comprara n con n-1
        //desde la segunda pagina verificar si division es vacio o diferente y terminar cuando cambie
        for (int i = 1; i < numberOfPages; i++) {
            page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i);
            String division_next = get_text_by_area(region_div, page_from, i);
            //verificar que div_next sea igual que div, o vacio, por que la hoja vacia hace parte de div
            if (division_next.equals(division) || division_next.equals("")) {

                //si es igual al anterior aadir la pagina al documento
                document_to.addPage(page_from);
                //obtener programas de las siguientes hojasn
                if (!division_next.equals("")) {
                    //si es la hoja vacia no buscar programas.
                    hash_programs(region_programa, page_from, division);
                }
            } else {
                //crear una estructura de resultados, division, periodo consolidado div.

                //File folder = new File(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+"\\"+periodo+"\\");
                File folder = new File("RES_" + periodo + "\\" + division + "\\");
                if (!folder.exists()) {
                    folder.mkdirs();
                }

                // document_to.save(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+"\\"+periodo+"\\"+type+".pdf");
                document_to.save("RES_" + periodo + "\\" + division + "\\" + type + ".pdf");

                //Preparacion para la siguiente iteracion 
                //crear un nuevo documento
                document_to = new PDDocument();
                //aadir la pagina encontrada que es diferente a la anterior
                page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i);
                document_to.addPage(page_from);
                //obtener datos de la  pagina
                division = get_text_by_area(region_div, page_from, i);
                periodo = get_text_by_area(region_periodo, page_from, i);
                hash_programs(region_programa, page_from, division);

            }

        }
        //ultima iteracion
        //create directory if not exist:
        // File folder = new File(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\");
        File folder = new File("RES_" + periodo + "\\" + division + "\\");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // document_to.save(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+"\\"+type+".pdf");
        document_to.save("RES_" + periodo + "\\" + division + "\\" + type + ".pdf");

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

    //get periodo

    //get programa

}

From source file:FeatureExtraction.FeatureExtractorPDFStructuralPaths.java

/**
 * Return true if the PDF is compatible/*from w w  w . j a  va2s. com*/
 *
 * @param filePath pdf file path
 * @return true if the PDF is compatible
 */
public boolean IsCompatiblePDF2(String filePath) {
    File pdfFile = new File(filePath);
    Map<String, Integer> structuralPaths = new HashMap<>();
    HashSet<COSBase> visitedObjects = new HashSet<>();
    boolean compatible = true;
    PDDocument pdf = new PDDocument();
    COSDocument pdfDocument = new COSDocument();
    String parentPath = "";
    String pdfObjectName = "Trailer";
    try {
        pdf = PDDocument.load(pdfFile);
        pdfDocument = pdf.getDocument();
        ExtractPDFStructuralPathsRecursively(pdfDocument.getTrailer().getCOSObject(), pdfObjectName, parentPath,
                structuralPaths, visitedObjects, 1);
    } catch (IOException e) {
        compatible = false;
    } finally {
        try {
            pdf.close();
            pdfDocument.close();
        } catch (IOException e) {
            Console.PrintException(String.format("Error closing PDF file: '%s'", filePath), e);
        }
    }
    return compatible;
}

From source file:FeatureExtraction.FeatureExtractorPDFStructuralPathsOld.java

/**
 * Return true if the PDF is compatible//from  w ww  . j  ava 2s.  co m
 *
 * @param filePath pdf file path
 * @return true if the PDF is compatible
 */
public boolean IsCompatiblePDF2(String filePath) {
    File pdfFile = new File(filePath);
    Map<String, Integer> structuralPaths = new HashMap<>();
    HashSet<COSBase> visitedObjects = new HashSet<>();
    boolean compatible = true;
    PDDocument pdf = new PDDocument();
    COSDocument pdfDocument = new COSDocument();
    try {
        pdf = PDDocument.load(pdfFile);
        pdfDocument = pdf.getDocument();
        ExtractPDFStructuralPathsRecursively(pdfDocument.getTrailer().getCOSObject(), "Trailer", "",
                structuralPaths, visitedObjects);
    } catch (IOException e) {
        compatible = false;
    } finally {
        try {
            pdf.close();
            pdfDocument.close();
        } catch (IOException e) {
            Console.PrintException(String.format("Error closing PDF file: '%s'", filePath), e);
        }
    }
    return compatible;
}

From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java

License:Apache License

/**
 * creates a sample document with some text using a text matrix.
 * //from  ww  w.  j  ava  2 s .c om
 * @param message
 *            The message to write in the file.
 * @param outfile
 *            The resulting PDF.
 * 
 * @throws IOException
 *             If there is an error writing the data.
 * @throws COSVisitorException
 *             If there is an error writing the PDF.
 */
public void doIt(String message, String outfile) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // Page 1
        PDFont font = PDType1Font.HELVETICA;
        PDPage page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        float fontSize = 12.0f;

        PDRectangle pageSize = page.findMediaBox();

        System.err.println("pageSize " + pageSize);
        System.err.println(
                "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54);

        float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f;
        float stringWidth = font.getStringWidth(message);
        float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();
        // counterclockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition,
                    pageSize.getHeight() - centeredYPosition);
            contentStream.drawString(message + " " + i);
        }
        // clockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition);
            contentStream.drawString(message + " " + i);
        }

        contentStream.endText();
        contentStream.close();

        // Page 2
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        // text scaling
        for (int i = 0; i < 10; i++) {
            contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50);
            contentStream.drawString(message + " " + i);
        }
        contentStream.endText();
        contentStream.close();

        // Page 3
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        int i = 0;
        // text scaling combined with rotation
        contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.endText();
        contentStream.close();

        // Page 4
        {
            page = new PDPage();
            page.setMediaBox(PDPage.PAGE_SIZE_A4);
            doc.addPage(page);
            fontSize = 1.0f;

            contentStream = new PDPageContentStream(doc, page, false, false);
            contentStream.setFont(font, fontSize);
            contentStream.beginText();

            AffineTransform root = new AffineTransform();
            root.scale(72.0 / 2.54, 72.0 / 2.54);

            for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) {
                // text scaling combined with rotation
                {
                    AffineTransform rowMatrix = new AffineTransform(root);
                    rowMatrix.translate(1, i);
                    contentStream.setTextMatrix(rowMatrix);
                    contentStream.drawString(message + " " + i);
                }

            }

            contentStream.endText();
            contentStream.close();
        }

        doc.save(outfile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}