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:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);// w w w .  ja  v  a2  s. c  om
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:model.objects.Project.java

License:Apache License

public void savePDF(final String firstPath) throws IOException {

    PDDocument doc = document.getPDDocument();
    System.out.println(doc);//  w w  w.  j  a  va2  s. com
    try {

        final boolean newlyCreated = (doc == null);

        if (newlyCreated) {

            // create new document and insert empty page to the document.
            doc = new PDDocument();
        } else {
            // reset wrong settings.
            State.setBorderBottomPercentExport(0);
            State.setBorderRightPercentExport(0);
            State.setBorderLeftPercentExport(0);
            State.setBorderTopPercentExport(0);
            State.setExportAlpha(true);
        }

        for (int i = 0; i < pictures.length; i++) {
            int index = i + 0;
            if (newlyCreated) {
                index = -1;
            }

            attatchToPDF(doc, pictures[i].getBufferedImage(0, 0, false), index);
        }

        //save and close
        doc.save(firstPath);
    } finally {
        if (doc != null) {
            //                doc.close();
        }
    }
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile    pdf input//from www.  ja  va 2 s. c o m
 * @param _imagePath    image input
 * @param _outputFile    pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void saveAsPdf(String _imagePath, String _outputFile) throws IOException {

    PDDocument doc = null;
    try {

        // create new document and insert empty page to the document.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

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

From source file:model.util.pdf.XDocument.java

License:Apache License

/**
 * Call super-class constructor and initialize extra-
 * settings.//from  w w w.j  a va2 s .c om
 */
public XDocument() {

    // call super constructor.
    super();
    this.document = new PDDocument();
}

From source file:net.padaf.preflight.xmp.TestSynchronizedMetadataValidation.java

License:Apache License

@Before
public void initNewDocumentInformation() throws Exception {

    try {/*w  ww .j a  va  2 s  . co  m*/
        doc = new PDDocument();
        dico = doc.getDocumentInformation();
        metadata = new XMPMetadata();
    } catch (IOException e) {
        throw new Exception("Failed to create temporary test PDF/XMP Document");
    }

}

From source file:nominas.sei.form.Principal.java

private void ordenaNominas(String rutaEntrada, String rutaSalida) {
    ArrayList<PaginaNomina> paginasNomina = new ArrayList<PaginaNomina>();

    for (int x = 0; x < 1; x++) {//RECORREMOS EL ARREGLO CON LOS NOMBRES DE ARCHIVO

        try {/*w w w  . j  a v  a 2  s .co m*/
            PDDocument pd = PDDocument.load(rutaEntrada); //CARGAR EL PDF
            List l = pd.getDocumentCatalog().getAllPages();//NUMERO LAS PAGINAS DEL ARCHIVO
            Object[] obj = l.toArray();//METO EN UN OBJETO LA LISTA DE PAGINAS PARA MANIPULARLA
            for (int i = 0; i < l.size(); i++) {
                PDPage page = (PDPage) obj[i];//PAGE ES LA PAGINA 1 DE LA QUE CONSTA EL ARCHIVO
                PageFormat pageFormat = pd.getPageFormat(0);//PROPIEDADES DE LA PAGINA (FORMATO)
                Double d1 = new Double(pageFormat.getHeight());//ALTO
                Double d2 = new Double(pageFormat.getWidth());//ANCHO
                int width = d1.intValue();//ANCHO
                int eigth = 1024;//ALTO

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();//COMPONENTE PARA ACCESO AL TEXTO
                Rectangle rect = new Rectangle(0, 0, width, eigth);//DEFNIR AREA DONDE SE BUSCARA EL TEXTO
                stripper.addRegion("area1", rect);//REGISTRAMOS LA REGION CON UN NOMBRE
                stripper.extractRegions(page);//EXTRAE TEXTO DEL AREA

                String contenido = new String();//CONTENIDO = A LO QUE CONTENGA EL AREA O REGION
                contenido = (stripper.getTextForRegion("area1"));
                String[] lines = contenido.split("[\\r\\n]+");
                String nombre = lines[1].substring(28, lines[1].length() - 10);//Separamos el nombre
                PaginaNomina nomina = new PaginaNomina(page, nombre);
                paginasNomina.add(nomina);
            }
            Collections.sort(paginasNomina);
            // Create a new empty document
            PDDocument document = new PDDocument();

            for (int i = 0; i < paginasNomina.size(); i++) {
                System.out.println(paginasNomina.get(i).getNombre());
                document.addPage(paginasNomina.get(i).getPagina());
            }
            // Save the newly created document
            document.save(rutaSalida);

            // finally make sure that the document is properly
            // closed.
            document.close();
            pd.close();//CERRAMOS OBJETO ACROBAT
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } //CATCH
    } //FOR
}

From source file:nominas.sei.NominasSEI.java

/**
 * @param args the command line arguments
 *//*from www.  jav  a 2  s.com*/
public static void main(String[] args) {

    ArrayList<PaginaNomina> paginasNomina = new ArrayList<PaginaNomina>();

    for (int x = 0; x < 1; x++) {//RECORREMOS EL ARREGLO CON LOS NOMBRES DE ARCHIVO
        String ruta = new String();//VARIABLE QUE DETERMINARA LA RUTA DEL ARCHIVO A LEER.
        ruta = (".\\NOMINAS.pdf"); //SE ALMACENA LA RUTA DEL ARCHIVO A LEER. 

        try {
            PDDocument pd = PDDocument.load(ruta); //CARGAR EL PDF
            List l = pd.getDocumentCatalog().getAllPages();//NUMERO LAS PAGINAS DEL ARCHIVO
            Object[] obj = l.toArray();//METO EN UN OBJETO LA LISTA DE PAGINAS PARA MANIPULARLA
            for (int i = 0; i < l.size(); i++) {
                PDPage page = (PDPage) obj[i];//PAGE ES LA PAGINA 1 DE LA QUE CONSTA EL ARCHIVO
                PageFormat pageFormat = pd.getPageFormat(0);//PROPIEDADES DE LA PAGINA (FORMATO)
                Double d1 = new Double(pageFormat.getHeight());//ALTO
                Double d2 = new Double(pageFormat.getWidth());//ANCHO
                int width = d1.intValue();//ANCHO
                int eigth = 1024;//ALTO

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();//COMPONENTE PARA ACCESO AL TEXTO
                Rectangle rect = new Rectangle(0, 0, width, eigth);//DEFNIR AREA DONDE SE BUSCARA EL TEXTO
                stripper.addRegion("area1", rect);//REGISTRAMOS LA REGION CON UN NOMBRE
                stripper.extractRegions(page);//EXTRAE TEXTO DEL AREA

                String contenido = new String();//CONTENIDO = A LO QUE CONTENGA EL AREA O REGION
                contenido = (stripper.getTextForRegion("area1"));
                String[] lines = contenido.split("[\\r\\n]+");
                String nombre = lines[1].substring(28, lines[1].length() - 10);
                PaginaNomina nomina = new PaginaNomina(page, nombre);
                paginasNomina.add(nomina);
            }
            Collections.sort(paginasNomina);
            // Create a new empty document
            PDDocument document = new PDDocument();

            for (int i = 0; i < paginasNomina.size(); i++) {
                System.out.println(paginasNomina.get(i).getNombre());
                document.addPage(paginasNomina.get(i).getPagina());
            }
            // Save the newly created document
            document.save("NominasOrdenadas.pdf");

            // finally make sure that the document is properly
            // closed.
            document.close();
            pd.close();//CERRAMOS OBJETO ACROBAT
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } //CATCH
    } //FOR

}

From source file:openstitcher.core.PDFRenderer.java

License:Open Source License

public static void render(Design design, String location, ArrayList<LegendEntry> legend)
        throws IOException, COSVisitorException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);/* w  w  w. j  ava  2 s  .  c  o  m*/
    PDFont font = PDType1Font.HELVETICA;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    float sideMargin = 70.0f;
    float capsMargin = 30.0f;

    // draw the document title
    contentStream.beginText();
    contentStream.setFont(font, 24.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - 24.0f);
    contentStream.drawString(design.title);
    contentStream.endText();

    // draw the document author
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f));
    contentStream.drawString(design.author);
    contentStream.endText();

    // draw the document license
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f));
    contentStream.drawString(design.license);
    contentStream.endText();

    // draw the physical size
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(pageWidth - sideMargin - 100.0f,
            pageHeight - capsMargin - (24.0f + 12.0f + 12.0f));
    contentStream.drawString(design.physicalSize);
    contentStream.endText();

    // draw the pattern
    float gridWidth = pageWidth - (sideMargin * 2);
    float widthPerCell = gridWidth / (float) design.pattern.getPatternWidth();
    float gridStartX = sideMargin;
    float gridStopX = sideMargin + (widthPerCell * design.pattern.getPatternWidth());
    float gridStartY = pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f);
    float gridStopY = (pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f))
            - (widthPerCell * design.pattern.getPatternHeight());

    // draw the pattern: background
    for (int i = 0; i < design.pattern.getPatternWidth(); i++) {
        for (int j = 0; j < design.pattern.getPatternHeight(); j++) {
            Yarn cellYarn = design.pattern.getPatternCell(i, j);
            if (cellYarn != null) {
                contentStream.setNonStrokingColor(cellYarn.color);
                contentStream.fillRect(gridStartX + (widthPerCell * i),
                        gridStartY - (widthPerCell * j) - widthPerCell, widthPerCell, widthPerCell);
            }

        }
    }

    // draw the pattern: grid outline
    contentStream.setStrokingColor(Color.black);
    for (int i = 0; i < design.pattern.getPatternWidth() + 1; i++) {
        // draw vertical lines
        float xCoord = gridStartX + (widthPerCell * i);
        if (i % 5 == 0) {
            contentStream.setLineWidth(2.0f);
        } else {
            contentStream.setLineWidth(1.0f);
        }
        contentStream.drawLine(xCoord, gridStartY, xCoord, gridStopY);
    }
    for (int i = 0; i < design.pattern.getPatternHeight() + 1; i++) {
        // draw horizontal lines
        float yCoord = gridStartY - (widthPerCell * i);
        if (i % 5 == 0) {
            contentStream.setLineWidth(2.0f);
        } else {
            contentStream.setLineWidth(1.0f);
        }
        contentStream.drawLine(gridStartX, yCoord, gridStopX, yCoord);
    }

    // draw the pattern: characters
    contentStream.setNonStrokingColor(Color.black);
    float centeringOffset = widthPerCell / 5.0f;
    for (int i = 0; i < design.pattern.getPatternWidth(); i++) {
        for (int j = 0; j < design.pattern.getPatternHeight(); j++) {
            Yarn cellYarn = design.pattern.getPatternCell(i, j);
            if (cellYarn != null) {
                int index = LegendEntry.findIndexByYarn(legend, cellYarn);
                if (index == -1) {
                    throw new RuntimeException("Cell did not exist in legend.");
                }
                contentStream.beginText();
                contentStream.setFont(font, widthPerCell);
                contentStream.moveTextPositionByAmount(gridStartX + (widthPerCell * i) + centeringOffset,
                        gridStartY - (widthPerCell * j) - widthPerCell + centeringOffset);
                contentStream.drawString(legend.get(index).character);
                contentStream.endText();
            }
        }
    }

    // draw the legend
    float legendWidth = pageWidth - (sideMargin * 2);
    float widthPerLegendCell = legendWidth / (float) legend.size();
    float legendStartX = sideMargin;
    float legendStopX = pageWidth - sideMargin;
    float legendStartY = capsMargin + 12.0f;
    float legendStopY = capsMargin;
    float legendCellPadding = 1.0f;
    float exampleCellWidth = 10.0f;

    for (int i = 0; i < legend.size(); i++) {
        // draw box
        contentStream.setNonStrokingColor(legend.get(i).yarn.color);
        contentStream.fillRect(legendStartX + legendCellPadding + (i * widthPerLegendCell),
                legendStopY + legendCellPadding, exampleCellWidth, exampleCellWidth);

        // draw character
        contentStream.beginText();
        contentStream.setNonStrokingColor(legend.get(i).fontColor);
        contentStream.setFont(font, 10.0f);
        contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + (i * widthPerLegendCell),
                legendStopY + legendCellPadding);
        contentStream.drawString(legend.get(i).character);
        contentStream.endText();

        // draw yarn name
        contentStream.beginText();
        contentStream.setNonStrokingColor(Color.black);
        contentStream.setFont(font, 10.0f);
        contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + exampleCellWidth
                + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding);
        contentStream.drawString(legend.get(i).yarn.name);
        contentStream.endText();
    }

    contentStream.close();
    document.save(location);
    document.close();
}

From source file:org.alfresco.repo.content.transform.OOoContentTransformerHelper.java

License:Open Source License

/**
 * This method produces an empty PDF file at the specified File location.
 * Apache's PDFBox is used to create the PDF file.
 *///from   w ww  .j  a v  a  2  s. c  o  m
private void produceEmptyPdfFile(File tempToFile) {
    // If improvement PDFBOX-914 is incorporated, we can do this with a straight call to
    // org.apache.pdfbox.TextToPdf.createPDFFromText(new StringReader(""));
    // https://issues.apache.org/jira/browse/PDFBOX-914

    PDDocument pdfDoc = null;
    PDPageContentStream contentStream = null;
    try {
        pdfDoc = new PDDocument();
        PDPage pdfPage = new PDPage();
        // Even though, we want an empty PDF, some libs (e.g. PDFRenderer) object to PDFs
        // that have literally nothing in them. So we'll put a content stream in it.
        contentStream = new PDPageContentStream(pdfDoc, pdfPage);
        pdfDoc.addPage(pdfPage);

        // Now write the in-memory PDF document into the temporary file.
        pdfDoc.save(tempToFile.getAbsolutePath());

    } catch (COSVisitorException cvx) {
        throw new ContentIOException("Error creating empty PDF file", cvx);
    } catch (IOException iox) {
        throw new ContentIOException("Error creating empty PDF file", iox);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException ignored) {
                // Intentionally empty
            }
        }
        if (pdfDoc != null) {
            try {
                pdfDoc.close();
            } catch (IOException ignored) {
                // Intentionally empty.
            }
        }
    }
}

From source file:org.apache.camel.component.pdf.PdfAppendTest.java

License:Apache License

@Test
public void testAppend() throws Exception {
    final String originalText = "Test";
    final String textToAppend = "Append";
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);// ww  w  .j  a va  2  s. co  m
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(originalText);
    contentStream.endText();
    contentStream.close();

    template.sendBodyAndHeader("direct:start", textToAppend, PdfHeaderConstants.PDF_DOCUMENT_HEADER_NAME,
            document);

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(ByteArrayOutputStream.class));
            try {
                PDDocument doc = PDDocument
                        .load(new ByteArrayInputStream(((ByteArrayOutputStream) body).toByteArray()));
                PDFTextStripper pdfTextStripper = new PDFTextStripper();
                String text = pdfTextStripper.getText(doc);
                assertEquals(2, doc.getNumberOfPages());
                assertThat(text, containsString(originalText));
                assertThat(text, containsString(textToAppend));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();

}